Bubble sort: Classic algorithm problem.
There is a set of numbers 2,10,8,20,11, which arranges the numbers in order from large to small. 20,11,10,8,2
2,10,8,20,11
Find the maximum number and put it in the first place (1,2,3,4,5)
20,10,8,2,11
From the remaining 4 numbers, find the largest (2,3,4,5)
20,11,8,2,10
From the remaining 3 numbers, find the largest (3,4,5)
20,11,10,2,8
From the remaining 2 numbers, find the largest (4,5)
20,11,10,8,2
Above is the teacher's steps, I did not look carefully first to think about
int[] A = {2,10,8,20,11}; BooleanPanduan =true; intnum = 0;System.out.println ("Output original array:");//Output Original Array for(inti:a) {System.out.print (i+" "); } System.out.println (); while(Panduan)//the outermost loop is set to a dead loop and only jumps out of the loop if the inner loop determines that the condition is satisfied. { for(inti = 0; i<4; i++)//I array subscript, because 4 is the last one, if the front runs normally, there is no need to compare. So the range is set to I<4 . { for(intj = 4; j>=0; j--)//J The array subscript , the element labeled I, and the elements in the array, in reverse order. { if(i = = J | | i > J)//when i = J or i>j, if the front runs correctly, does not need to be compared, and does not continue to run, so jump out of the variable is J Loop, continue to execute the variable i loop { Break ; }Else if(A[i]<a[j])//when a condition is met, the position of the two element is exchanged{A[i]= a[i]+A[j]; A[J]= A[i]-A[j]; A[i]= A[i]-A[j]; } } } for(intk = 0; K <4; k++)//the detection loop is used to determine if the current array is reaching the condition { for(intL = 4; l >= 0; l--) { if(k = = L | | k >l) { Break ; }Else if(A[k]>a[l])//Judging size{num++;//if the condition is correct, num+1 } } } if(num = = 10)//if the conditions are correct, then num should be added 10 times, so when num=10, the Panduan value of the Boolean value is changed to False, you can jump out of the while loop.{Panduan=false; } num= 0;//If a loop reaches the desired array, num is returned to 0, and the loop continues until it is correct. }//While End BracketSYSTEM.OUT.PRINTLN ("Output sorted after array:"); for(intm:a) {System.out.print (M+" "); } }}
(Beginner Java, blog record-based, light spray, error presumably a lot, if you can point out, grateful, part of the content is not original, from Baidu)
Java Bubble Sorting Classic algorithm problem