Bubble sorting algorithm is a simple and stable sorting algorithm, the time complexity of the algorithm is preferably O (n), the worst is O (n^2), the space complexity required is O (1).
The stability of the algorithm here means that after ordering, the elements can still maintain their relative order before ordering, it is said that the algorithm is stable, conversely, it is unstable.
For example, a set of numbers is preceded by a a1,a2,a3,a4,a5, where a2=a4, after some sort of a1,a2,a4,a3,a5, indicates that the sort is stable because A2 is preceded before and after A4; if the result of sorting is A1,A4,A2,A3,A5, Then the order is not stable. ------From the Java Programmer interview written book
A more common bubble sorting algorithm is as follows:
1 /**2 * Bubble Sort3 * @paramdata input as an array of shapes to be sorted4 */5 Public Static int[] Bubblesort (int[] data) {6 intSize =data.length;7 for(inti=0;i<size-1;i++){8 for(intj=0;j<size-1-i;j++){9 if(data[j]>data[j+1]){Ten inttemp =Data[j]; OneDATA[J] = data[j+1]; ADATA[J+1] =temp; - } - } the } - returndata; -}
As you can see, the classic bubble sort is chosen to start at one end, by comparing the size of adjacent elements and exchanging orders. In fact, the bubble sort is improved, ordered from both ends, so-called "two-way bubble sort", can have better efficiency. If the result of the order from small to large output, you can follow the "larger bubbles from left to right, smaller bubbles from right to left" to achieve the effect of two-way bubble sort; The implementation code (Java version) is as follows:
1 /**2 * Bidirectional bubble sort3 * @paramNum4 */5 Public Static int[] Doublebuddlesort (int[] num) {6 intLeft=0,right = num.length-1;7 while(left<Right ) {8 //larger bubbles move from left to right9 for(inti=left+1;i<=right;i++){Ten if(num[left]>Num[i]) { One inttemp =Num[left]; ANum[left] =Num[i]; -Num[i] =temp; - } the } -left++; - - //small bubbles move from right to left + for(inti=right-1;i>=left;i--){ - if(num[i]>Num[right]) { + inttemp =Num[right]; ANum[right] =Num[i]; atNum[i] =temp; - } - } -right--; - } - in returnnum; -}
Java version Two-way bubble sorting algorithm