java 数组的冒泡排序

时间:2023-03-09 03:47:24
java 数组的冒泡排序

  

冒泡排序
(1)冒泡排序算法的运作如下:(从后往前)
  1. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
  2. 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
  3. 针对所有的元素重复以上的步骤,除了最后一个。
  4. 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
(2)代码展示(java)
  int scoreArray2 []=new int [] {10,32,43,57,85,95,43,78,90,56};
  int count=0;//定义交换的次数
  int count2=0;//定义比较的次数
  for (int i = 0; i < scoreArray2.length; i++){
    for (int j = i+1; j < scoreArray2.length; j++){
      if(scoreArray2[i]>scoreArray2[j]){
        int temp=scoreArray2[j];
        scoreArray2[j]=scoreArray2[i];
        scoreArray2[i]=temp;
        count++;
      }
      count2++;
    }
  }
   //for-each遍历排序后的数组
  for (int i : scoreArray2){
    System.out.println(i);
  }
  System.out.println("共交换了"+count+"次");
  System.out.println("共比较了"+count2+"次");
  冒泡排序的核心代码就是交换
   int temp=scoreArray2[j];
   scoreArray2[j]=scoreArray2[i];
   scoreArray2[i]=temp;
  比较次数固定,速度慢,当数据量大时就不适用了