Bubble sort (Bubble sort) is a simple sort algorithm. Each time the adjacent two numbers are compared, they are exchanged if their positions do not match.
Each comparison, the number of comparisons will be reduced one time, because the previous is better.
For example:
First time, compare 8 and 9, because 9 is greater than 8, so swap their positions
The first time second, compare 8 and 7, because 8 is greater than 7, so their position is unchanged
The first time third, compare 7 and 1, because 7 is greater than 1, so their position is unchanged
The first time fourth times, compare 1 and 5, because 5 is greater than 1, so swap their positions
The first time fifth times, compare 1 and 2, because 2 is greater than 1, so swap their positions
The following comparisons are similar
Key Code Snippet:
1 Public Static voidMain (string[] args) {2 3 int[] score = {8, 9, 7, 1, 5, 2};4 5 for(inti = 0; i < score.length-1; i++){6 for(intj = 0;j < score.length-1-I; J + +){7 if(Score[j] < Score[j + 1]){8 intTMP =Score[j];9SCORE[J] = score[j + 1];TenScore[j + 1] =tmp; One } A } - } -}
Memory bubble sort just need to remember a formula: Outer loop Array Length-1, inner loop array length -1-i
Java sorting algorithm--bubble sort