The bubble sort principle is to assume that an array has n digits to be sorted, compare the first two numbers in the array, exchange them if they do not conform to the rules, then swap the second and third numbers, and so on, and so on, the first round of comparisons is that the largest or smallest value in this array is the last one in the array. Then the second round or repeat the first round of action, the final result is the unordered array of the largest or smallest value, stored in the second-to-last bit of the array. Then repeat the work in turn. The last round is a comparison of the first two numbers, resulting in a larger or smaller deposit in the second place. The entire array is sorted to completion. The code implemented with Java is as follows:
public static void bubblesort ([] array) { Span style= "color: #0000ff;" >for (int i =0; i<array.length-1;i++) { for (int J=0;j<array.lengt H-i-1; J++ if (Array[j] > array[j+1< Span style= "color: #000000;" >] { int temp = Array[j]; ARRAY[J] = Array[j+1]; Array[j +1] = temp; } } } }
The time complexity of the bubble sort is O (n^2) and the space complexity is: O (1)
Bubble Sort algorithm