冒泡排序算法的運作如下:
- 比較相鄰的元素猫十。如果第一個比第二個大,就交換他們兩個滑肉。
2.對每一對相鄰元素作同樣的工作,從開始第一對到結(jié)尾的最后一對摘仅。在這一點靶庙,最后的元素應(yīng)該會是最大的數(shù)。 - 針對所有的元素重復以上的步驟实檀,除了最后一個。
4.持續(xù)每次對越來越少的元素重復上面的步驟按声,直到?jīng)]有任何一對數(shù)字需要比較膳犹。
public class BubbleSort{
public static void main(String[] args){
int score[] = {67, 69, 75, 87, 89, 90, 99, 100};
for (int i = 0; i < score.length -1; i++){ //最多做n-1趟排序
for(int j = 0 ;j < score.length - i - 1; j++){ //對當前無序區(qū)間score[0......length-i-1]進行排序(j的范圍很關(guān)鍵,這個范圍是在逐步縮小的)
if(score[j] < score[j + 1]){ //把小的值交換到后面
int temp = score[j];
score[j] = score[j + 1];
score[j + 1] = temp;
}
}
System.out.print("第" + (i + 1) + "次排序結(jié)果:");
for(int a = 0; a < score.length; a++){
System.out.print(score[a] + "\t");
}
System.out.println("");
}
System.out.print("最終排序結(jié)果:");
for(int a = 0; a < score.length; a++){
System.out.print(score[a] + "\t");
}
}
}