Java sorting algorithm (iv): bubbling sort
Bubble sort is a sort of computer, and its time complexity is O (n^2), although it is less than heap sort, quick sort O (Nlogn, base 2). But there are two advantages
1, programming complexity is very low. It's easy to write code
2, with stability, here is the stability of the original sequence of the same elements of the relative order is still maintained to a sorted order. Heap sorting and fast sorting are not stable
But all the way, the second merge sort and the unbalanced binary tree sort speed are faster than the bubble sort speed, and have the stability, but the speed is not as fast as the heap sort, the quick sort. The bubbling sort is done by n-1, and the number of the sub-order from 1th to N-i is the first. If the number of I is greater than the next number (ascending, small, descending) then two numbers are exchanged.
The bubble sort algorithm is stable, O (1) space, the time complexity of comparison and Exchange is O (n^2). Adaptive, for an algorithm that has a basic ordering, the time complexity is O (n). Many properties of the bubbling sorting algorithm are similar to the insertion algorithm. But it's a little bit higher for the system overhead.
Sorting process
Imagine that the sorted array R[1..N] is vertically set. Each element is considered to be a weight bubble. According to the principle that the light cannon cannot be under the heavy bubbles, scan the array r from bottom to top. Where scanning is a slight bubble that violates this principle. So that it floats upward. So repeated. Until the last of any two bubbles are light in the upper weight under the principle.
Code implementation
Packagecom.spring.test;Importsun.nio.cs.ext.ISCII91;/*** Bubble Sort Test*/ Public classBubblesorttest { Public Static voidMain (string[] args) {int[] Data5 =New int[] {5, 3, 6, 2, 1, 9, 4, 8, 7}; Print (DATA5); Bubblesort (DATA5); System.out.println ("Sorted Array"); Print (DATA5); } /*** Bubble Sort *@paramData*/ Public Static voidBubblesort (int[] data) { for(inti = 0;i < data.length-1;i++){ Booleanissorted =false; for(intj=0;j<data.length-i-1;j++){ if(Data[j] > data[j+1]) {Swap (Data,j,j+1); IsSorted=true; print (data); } } if(!issorted) { //End Sort If the array is already in an orderly state Break; } } } /*** Exchange of two data *@paramData *@paramI *@paramJ*/ Public Static voidSwapint[] Data,intIintj) { if(i==j) { return ; } Data[i]= Data[i] +Data[j]; DATA[J]= Data[i]-Data[j]; Data[i]= Data[i]-Data[j]; } /*** Print output to an array *@paramData*/ Public Static voidPrintint[] data) { for(inti=0;i<data.length;i++) {System.out.print (Data[i]+ "\ T"); } System.out.println (); }}
Run results
Java sorting algorithm (iv): bubbling sort