java冒泡排序

99 阅读1分钟
public void bubble(){
  //定义一个数组:
  int[] num = {6,5,9,1,2,4};
  //使用循环:外层循环表示需要排序多少趟,num.length-1=5,保证进行5次排序
  for(int i = 0;i < num.length-1;i++){
     //使用循环,完成每一趟排序中的所有比较,注意:每多比较一趟,则少比较一次
     for(int j = 0;j < num.length-1-i;j++){
        //两个相邻的两个数进行比较:
        if(num[j] > num[j+1]){
             //前面的数比后面的数大,则交换
             int temp = num[j];
             num[j] = num[j+1];
             num[j+1] = temp;
         }
     }
  }  
}