Bubble sort (Bubble sort) is a simple sort algorithm. It repeatedly visited the sequence to sort, comparing two elements at a time, and swapping them out if they were wrong in the order. The work of the sequence of visits is repeated until no more need to be exchanged, that is, the sequence is sorted. The algorithm is named because the smaller elements will slowly "float" through the switch to the top of the sequence.
The bubbling sorting algorithm works as follows:
- Compares the adjacent elements. If the first one is bigger than the second one, swap them both.
- Do the same for each pair of adjacent elements, starting with the last pair from the first pair to the end. At this point, the last element should be the maximum number.
- Repeat the above steps for all elements, except for the last one.
- Repeat the above steps each time for fewer elements, until there are no pairs of numbers to compare.
1 Public classbubblesort{2 Public Static voidMain (string[] args) {3intScore[] = {67, 69, 75, 87, 89, 90, 99, 100}; 4 for(inti = 0; i < score.length-1; i++) {//up to do n-1 sort of trip5 for(intj = 0; J < score.length-i-1; J + +) {//sort the current unordered interval score[0......length-i-1] (the range of J is critical, the range is gradually shrinking)6if(Score[j] < Score[j + 1]) {//swap the small value to the back7inttemp =Score[j];8 Score[j] = score[j + 1]; 9 Score[j + 1] =temp;10 }11 } System.out.print ("No." + (i + 1) + "Order results:");13 for(intA = 0; A < Score.length; a++){System.out.print (Score[a] + "\ T");15 }System.out.println ("");17 }System.out.print ("Final sort result:");19 for(intA = 0; A < Score.length; a++){System.out.print (Score[a] + "\ T");21st }22 }23}
Java, bubble Sort method, online lookup