One, the simplest sort of rough
Thought: Let every keyword be compared with every key word behind it,
If the interchange is large, then the keyword in the first position must become the minimum after a loop.
1 Packagedemo01;2 3 classBubbleSort01 {4 Public Static voidMain (string[] args) {5 int[] n = {0,5,2,6,9,3,4,8,1,10,82,100,52,35,46,7};6 inti,j;7 for(intx=1;x<n.length;x++){8System.out.print (N[x] + ",");9 }TenSystem.out.println (""); One A for(i=1;i<n.length;i++){ - for(j=i+1;j<n.length;j++){ - if(n[i]>N[j]) { the inttemp =N[i]; -N[i] =N[j]; -N[J] =temp; - } + } - } + A for(intx=1;x<n.length;x++) atSystem.out.print (n[x]+ ","); - } -}
Second, the authentic bubble sort
Thought:
when the outer loop is 1(cyclic variable i=1), the inner loop (variable J) is compared from large to small, 22,
change the smaller value to the front, the minimum of the path to the front, and start the Next loop ( i=2 ), an analogy ......
1 Packagedemo01;2 3 classBubbleSort02 {4 Public Static voidMain (string[] args) {5 int[] n = {0,5,2,6,9,3,4,8,1};6 inti,j;7 for(intx=1;x<n.length;x++){8System.out.print (N[x] + ",");9 }TenSystem.out.println (""); One A for(i=1;i<n.length;i++){ - for(j=n.length-1;j>=2;j--){ - if(n[j]<n[j-1]){ the inttemp =N[j]; -N[J] = n[j-1]; -N[J-1] =temp; - } + } - } + A for(intx=1;x<n.length;x++) atSystem.out.print (n[x]+ ","); - } -}
Three, the optimized bubble sort algorithm
Thought: On the basis of the above algorithm, the steps of exchanging data are tagged, that is, if data exchange occurs, the value of the tag will change.
When an outer loop is in progress, the value of the tag bit is always the same, indicating that there is no exchange of values for this loop, that is, the order is complete.
1 Packagedemo01;2 3 classBubbleSort03 {4 5 Public Static voidMain (string[] args) {6 int[] n = {0,5,2,6,9,3,4,7,8,1};7 8 for(intx=1;x<n.length;x++){9System.out.print (N[x] + ",");Ten } OneSystem.out.println (""); A - inti,j; - BooleanFlag =true;//flag as Flag the for(I=1;i<n.length && flag;i++){ -Flag =false;//Initialize Flag - for(j=n.length-1;j>=2;j--){ - if(n[j]<n[j-1]){ + inttemp =N[j]; -N[J] = n[j-1]; +N[J-1] =temp; AFlag =true; at } - } - } - - for(intx=1;x<n.length;x++) -System.out.print (n[x]+ ","); in } -}
Bubble sort Java