最简单的排序方法之一 冒泡排序

public class BubbleSort{


public static void main(String[] args) {
  int[] bubbleSort ={1,6,2,3,4,5}; //声明一组乱顺序的数组
  int hole ;//声明一个空值
  for(int i = 0; i < bubbleSort.length-1; i++){
  for(int j =0;j<bubbleSort.length -i-1;j++){
  //如果大于前面的数
  if(bubbleSort[j] > bubbleSort[j+1]){
  //进行交换
  hole = bubbleSort[j];
  bubbleSort[j] = bubbleSort[j+1];
  bubbleSort[j+1] = hole;
    }
  }  
}
  //遍历输出
  for(int items : bubbleSort){
  System.out.print(items+" ");
    }
  }
}

注:如果要进行由高到低的排序的话,只要把if判断里的>号换成<号就行了!

猜你喜欢

转载自www.cnblogs.com/Striveprt/p/9499514.html
今日推荐