Java排序之冒泡排序示例

参考地址:https://www.cnblogs.com/bjh1117/p/8335628.html
资料请参考上述网址,内容写的十分详细,发表本文只是因为刚申请了博客,想试试怎么发布博客。
/**

  • 冒泡排序:
  •  1.比较相邻的元素,如果第一个比第二个大,就交换他们两个;
  •  2.从第一对到最后一对作比较,每轮比较结束,本轮最大的元素被交换到最后一位;
  •  3.针对所有的元素重复以上的步骤,除了最后一个;
  •  4.持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
  • 冒泡排序算法总结:
  •  1.N 个元素需要排序 N-1 轮;
  •  2.第 i 轮需要比较 N-i 次;
  •  3.N个元素排序,需要比较 n(n-1)/2 次;
  •  4.冒泡排序的算法复杂度较高,为 O(n*n)。
    */
    package arrayTest;

import java.util.Arrays;

public class maoPaosort {

public static void main(String[] args) {
    int[] maoPao = {6, 2, 4, 1, 9, 5};
    System.out.println("原始数组是:" + Arrays.toString(maoPao));
    int target = 0;
    for(int i = 0;i<maoPao.length-1;i++){//外层控制循环次数
        for(int j = 0;j<maoPao.length-i-1;j++){//内层负责相邻数的比较
            if(maoPao[j]>maoPao[j+1]){
                target = maoPao[j];
                maoPao[j] = maoPao[j+1];
                maoPao[j+1] = target;
            }
            System.out.print("第 " + (i + 1) + " 轮排序第 " + (j + 1) + " 次比较结果:");
            for (int a = 0; a < maoPao.length; a++) {
                System.out.print(maoPao[a]+"\t");
            }
            System.out.println("");
        }
        System.out.println("------------------------------------------------------------------------");
    }
    System.out.print("最终排序结果:" + Arrays.toString(maoPao));
}

}

猜你喜欢

转载自www.cnblogs.com/forever-xiaohui/p/9588713.html