Bubble sort is one of our most commonly used sorting algorithms, which is based on the principle of traversing a sequence that is not ordered from the beginning, comparing each of the two adjacent elements, the larger (or smaller) elements are placed behind, and the largest (or smallest) element after a round of traversal has been put to the last Then repeat the previous steps in order to sort the unordered sequence, after traversing the n-1 wheel, the whole sequence is sorted (the nth wheel is unnecessary, because the n-1 wheel is sorted with only the last element left). Because this sort algorithm good one elements every time, like bubbling, so called bubble sort.
For a small example:
Arr[] = {6,1,5,3,2,4}
First trip, 6, 1,5,3,2,4:1,6, 5,3,2,4-1,5,6, 3,2,4-1,5,3,6, 2,4-1,5,3 , 2,6, 4, 1,5,3,2,4,6
second trip, 1 , 5,3,2,4,6 : 1,5 , 3,2,4,6 -> 1,3,5 , 2,4,6 -> 1,3,2,5 , 4,6 -> 1,3,2,4,5 , 6
third trip, 1 , 3,2,4,5 , 6 : 1,3 , 2,4,5 , 6 - > 1,2,3 , 4,5 , 6 -> 1,2,3,4 , 5 , 6  
IV, 1, 2,3,4,5,6 : 1,2, 3,4,5,6 , 1, 2, 3,4,5,6
V, 1, 2,3,4,5,6 : 1,2,3,4 ,5,6
Six times, 1,2,3,4,5,6 (unnecessary)
Reference Network Pictures:
The core code is as follows:
/*** Bubble sort, small to large*/ Public Static voidBubblesort (int[] arr) { //simply traverse the n-1 wheel for(inti = 0; i < arr.length-1; i++) { //Traverse from head to top position not ordered for(intj = 0; J < arr.length-i-1; J + +) { //22 comparison, big back put if(Arr[j] > arr[j + 1]) { inttemp =Arr[j]; ARR[J]= Arr[j + 1]; Arr[j+ 1] =temp; } } } }
Bubble sort is a stable sorting algorithm, time complexity O (N2), Spatial complexity O (1).
---bubble sort of the Java sorting algorithm