/*** Bubble Sort: Java * *@authorSkywang * @date 2014/03/11*/ Public classBubblesort {/** Bubble Sort * * Parameter description: * A--array to be sorted * N--The length of the array*/ Public Static voidBubbleSort1 (int[] A,intN) {inti,j; for(i=n-1; i>0; i--) { //put the largest data in a[0...i] at the end for(j=0; j<i; J + +) { if(A[j] > a[j+1]) { //Exchange A[j] and a[j+1] intTMP =A[j]; A[J]= A[j+1]; A[j+1] =tmp; } } } } /** Bubble sort (Improved version) * * Parameter Description: * A--the array to be sorted * N--The length of the array*/ Public Static voidBubbleSort2 (int[] A,intN) {inti,j; intFlag//Mark for(i=n-1; i>0; i--) {flag= 0;//adds a token that is marked true if an interchange occurs during a traversal, otherwise false. If a trip does not take place, the order is complete! //put the largest data in a[0...i] at the end for(j=0; j<i; J + +) { if(A[j] > a[j+1]) { //Exchange A[j] and a[j+1] intTMP =A[j]; A[J]= A[j+1]; A[j+1] =tmp; Flag= 1; } } if(flag==0) Break;//Exit Algorithm } } Public Static voidMain (string[] args) {inti; int[] A = {20,40,30,10,60,50}; System.out.printf ("Before sort:"); for(i=0; i<a.length; i++) System.out.printf ("%d", A[i]); System.out.printf ("\ n"); BubbleSort1 (A, a.length); //BubbleSort2 (A, a.length);System.out.printf ("After sort:"); for(i=0; i<a.length; i++) System.out.printf ("%d", A[i]); System.out.printf ("\ n"); }}
Bubble Sort Time complexity
The time complexity of the bubble sort is O (N2).
Suppose there are n numbers in the sorted sequence. The time complexity of traversing a trip is O (N), how many times do you need to traverse it? N-1 times! Therefore, the time complexity of the bubble sort is O (N2).
Bubble sort Stability
Bubbling sequencing is a stable algorithm that satisfies the definition of a stable algorithm.
Algorithm stability-assuming that there is a a[i]=a[j in the sequence, A[i] before the order, and A[i] is still in front of a[j before ordering). Then this sort algorithm is stable!
Reprinted from Http://www.cnblogs.com/skywang12345/p/3596232.html
Java Bubble sort