The idea of bubble sorting is to compare the adjacent two elements once, and compare the positions if the elements are smaller than the previous elements.
After a trip like this, the most important element falls on the last side, so the boundary of the inner Loop also comes out, that is, the last few elements that are not counted, namely n-i-1;
And the position that the outer loop needs to compare is n-2, if it exceeds the boundary; (where n is the total number of elements)
For example, there are a number of columns:
38, 49, 65, 76, 13, 27, 30, 97
Each trip is sorted as follows:
The following is the algorithm for bubbling sorting:
Public classBubblesort { Public int[] Sort (int[] arrays) { inttemp = 0; for(inti = 0; i < arrays.length-2; i++) { for(intj = 0; J < arrays.length-1-I; J + +) { if(Arrays[j] > arrays[j + 1]) {temp=Arrays[j]; ARRAYS[J]= Arrays[j + 1]; Arrays[j+ 1] =temp; } } } returnarrays; }}
The test classes are as follows:
Public classTest { Public Static voidMain (string[] args) {Bubblesort bubblesort=NewBubblesort (); int[] Array =Createarray (); LongCt1 =System.currenttimemillis (); int[] Arrays =Bubblesort.sort (array); LongCT2 =System.currenttimemillis (); display (arrays); System.out.println ("Time Consumed:" + (CT2-ct1)); } Public Static voidDisplayint[] arrays) {System.out.println ("Sorted Data:"); for(inti = 0; i < arrays.length; i++) {System.out.print (Arrays[i]+ "\ T"); if(i% 10 = = 0) {System.out.println (); }} System.out.println (); } Public Static int[] Createarray () {int[] Array =New int[10000]; System.out.println ("The elements in the array are:"); for(inti = 0; I < 10000; i++) {Array[i]= (int) (Math.random () * 1000); System.out.print (Array[i]+ "\ T"); if(i% 10 = = 0) {System.out.println (); }} System.out.println (); returnArray; }}
10,000 number after the bubble sort time is about 200ms, and 100,000 number is sorted by about 14000ms, this shows that the data volume under the condition of bubble sort;
Bubble sort (Java)