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
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.
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!