Home >Java >JavaBase >Java implements bubble sort algorithm

Java implements bubble sort algorithm

王林
王林forward
2019-11-29 17:26:102458browse

Java implements bubble sort algorithm

Introduction

Bubble sort is an algorithm that compares adjacent elements and, if they are in the wrong position, swaps them s position. Sorting can be done in ascending or descending order.

Principle

Start from the first element, compare the first element and the second element, if the first element is greater than the second element, then swap their location. Compare the positions of the second element and the third element, and if they are in the wrong position, swap them. The above process goes until the last element of the array.

Related video tutorial recommendations: java free video tutorial

Java implements bubble sort algorithm

The same process is applied to the remaining iterations, after each iteration , the largest element will be placed after the unsorted elements. After each iteration, the comparison ends at the last unsorted element. When the unsorted element is placed in the correct position, the sorting is completed.

Java implements bubble sort algorithm

Java implements bubble sort algorithm

Bubble sort algorithm

```
bubbleSort(array)
  	for i <- 1 to indexOfLastUnsortedElement-1
	    if leftElement > rightElement
	      swap leftElement and rightElement
end bubbleSort
```

<span style="font-size: 14px;">Java implementation</span>

// Bubble sort in Java

import java.util.Arrays;

class BubbleSort {
  void bubbleSort(int array[]) {
    int size = array.length;
    for (int i = 0; i < size - 1; i++)
      for (int j = 0; j < size - i - 1; j++)
        // To sort in descending order, change > to < in this line.
        if (array[j] > array[j + 1]) {
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
        }
  }
  public static void main(String args[]) {
    int[] data = { -2, 45, 0, 11, -9 };
    BubbleSort bs = new BubbleSort();
    bs.bubbleSort(data);
    System.out.println("Sorted Array in Ascending Order:");
    System.out.println(Arrays.toString(data));
  }
}

Recommended related articles and tutorials: java entry program

The above is the detailed content of Java implements bubble sort algorithm. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete