Time complexity if the initial state of the file is a positive sequence, a scan can be done in order. Number of keyword comparisons required and record the number of moves Have reached the minimum value: , . So, the best time to bubble sort is the complexity of . If the initial file is reversed, a sequencing is required. The Sub-keyword comparison (1≤i≤n-1) is performed for each order, and each comparison must move the record three times to reach the Exchange record location. In this case, the comparison and the number of moves have reached the maximum value: The worst time complexity for bubbling sorting is . The overall average time complexity of the bubble sort is . The algorithm's stability bubble sort is to move the small element forward or the large element to be adjusted backwards. The comparison is an adjacent two element comparison, and the interchange also occurs between these two elements. So, if the two elements are equal, I think you will not be bored to exchange them again, if the two equal elements are not adjacent, then even through the preceding 22 exchange two adjacent together, this time will not be exchanged, so the same elements of the order has not changed, so bubble sort is a stable sorting algorithm.
1 /**2 * Bubble Sort JAVA3 * Optimized bubble sorting4 * Add a issort whether this round has been sorted by the judgment, if not sorted then the sort has ended directly exit5 * @authorAdministrator6 * @time 201607317 */8 Public Abstract classBubblingsort {9 ////////////////Start Bubble SortTen Public Static int[] Sort (int[] array) One { A Booleanissort=false;//determines whether or not to sort, defaults to not being sorted, and ends directly if no sort is done - for(inti = 0; i < array.length-1; i++) { -issort=false;//set the sort identity to false before each round of sorting the for(intj = 0; J < Array.length-i-1; J + +) { - if(array[j]>array[j+1]) - { - intTemp =array[j+1]; +array[j+1]=Array[j]; -array[j]=temp; +issort=true;//If True then this round is exchanged to continue the next round A } at } - if(!issort) Break;//If there is no loop in this round, the result is false and jumps out without the next round of retrieval - } - returnArray//return Array - } - ///////////End Bubble Sort in}
I added a judge in the inside whether the sorting is finished, if the sort has been completed, then immediately end the sort, do not continue to cycle detection!
The method I called in another class:
1 Public classArithmetic_testclass {2 Public Static voidMain (string[] args) {3 //Test array int type4 intarray[]={4,9,5,3,7,6,8,3,2,1}; 5 6 //Bubble sort optimized bubble sort7array=Bubblingsort.sort (array);8 9 for(intI:array) {TenSystem.out.print (i+ ""); One } A - } -}
The results of the implementation are as follows:
1 2 3 3 4 5 6 7 8 9
Successful implementation!
Bubble Sort-Optimized