First, the principle of bubble sort
Bubble sort, that is, starting from the first element, through 22 exchange, so that the small first out, and then go to the second round to make the second small to come out, until the last round of the biggest out, sort of completed
Second, the bubble sort of pseudo-code implementation:
1 Bubblesort (A)2 {3 fori = 1To Length[a]4 {5 forj = Length[a] to i+16 {7 ifA[J] < A[j-1]8 {9Exchane A[j] and a[j-1];Ten } One } A } -}
Third, the bubble sort Java source code implementation
ImportJava.util.Comparator; Public classBubblesort {/*** Define a generic bubble sort method * Learn how to use generics and how to implement bubble sort * Generic types cannot be of the underlying type (such as Int,double,char, etc.) and must be of a reference type (such as Integer, double, C Haracter)*/ Public Static<T>voidBubblesort (t[] T, comparator<?SuperT>comparator) {T temp= T[0]; for(inti = 0; i < t.length-1; i + +) { for(intj = t.length-1; J >= I+1; J--) if(Comparator.compare (T[j-1], t[j]) > 0) {Temp= T[j-1]; T[j-1] =T[j]; T[J]=temp; } } } /** * @paramthe args * Main function is used for testing. */ Public Static voidMain (string[] args) {//TODO auto-generated Method StubInteger[] INTs = {2, 0, 5, 23, 1, 4, 8, 56, 19}; Bubblesort (INTs,NewComparator<integer> () { Public intCompare (integer O1, integer o2) {returnO1.intvalue ()-O2.intvalue (); } }); for(inti:ints) {System.out.print (i+ " "); } System.out.println (); }}
Operation Result:
Iv. Analysis of Complexity
O (n^2)
java-Sorting algorithm-bubble sort