冒泡排序

来源:互联网 发布:linux nat 编辑:程序博客网 时间:2024/06/10 20:08

过程:将第一个记录的关键字和第二个记录的关键字进行比较,如果后面的比前面的小则交换,然后比较第二个和第三个,依次类推。比完一趟,最大的那个已经放到了最后的位置,这样就可以对前面N-1(除最后一个最大的数)个数再循环比较。

==========================================================================================

package com.test.cn;


public class BubbleSort {
    
    public static void main(String[] args) {
        int score[] =  {100, 75, 69, 87, 89, 90, 99, 67};
        for (int i = 0; i < score.length-1; i++){        //比较(score.length-1)轮
            for (int j = 0;j < score.length-i-1; j++){  //对未排序数字(score.length-1-i)进行排序
                if (score[j] > score[j+1] ){                  //较大的数据排到后面。较小的数据排到前面。
                    int temp  = score[j];
                    score[j] = score[j+1];
                    score[j+1] = temp;
                }
            }
        System.out.println("第"+(i+1)+"次排序结果:");   //打印每轮排序結果
        for(int a = 0; a < score.length; a++){
            System.out.println(""+score[a]);
        }
        
      }
        System.out.println("最后總排序结果:");             //打印排序總結果
        for(int i =0;i <score.length;i++){
            System.out.print(score[i]+"   ");
        }
 
    }

}


0 0
原创粉丝点击