zoukankan      html  css  js  c++  java
  • 排序一:冒泡以及三种优化

    /**
     * 冒泡以及三种优化
     * */

    public class One {
        /**
         * 经典
       *N个数字要排序完成,总共进行N-1趟排序,每i趟的排序次数为(N-i)  *
    */ public static void one(int[] arr) { for(int i=0;i<arr.length-1;i++) { for(int j=1;j<arr.length-i;j++) { if(arr[j-1] > arr[j]) { int temp = arr[j-1]; arr[j-1] = arr[j]; arr[j] = temp; } } } } /** *优化一 ,加入标志,判断上一轮是否有过交换 **/ public static void two(int[] arr) { boolean exchange = false; for(int i=0;i<arr.length-1;i++) { //比较n-1趟 for(int j = 1;j <arr.length-i;j++) { //j从1开始, 有i个数据已经排序好了 if(arr[j-1] >arr[j]) { int temp = arr[j-1]; arr[j-1] = arr[j]; arr[j] = temp; if(!exchange) exchange = true; } } if(!exchange) break;//判断这一趟是否有交换数据,没有交换数据表明已经排好序 } } /** * 优化二,在每一趟中,对已经排好序的不去进行比较 * */ public static void three(int[] arr) { int end = 1; int pos = 1; while(end >0) { for(int j = 1;j <end;j++) { //j从1开始, 有i个数据已经排序好了 if(arr[j-1] >arr[j]) { int temp = arr[j-1]; arr[j-1] = arr[j]; arr[j] = temp; pos = j; } } end = pos - 1; } } /** * 优化三、每次循环,正反两次冒泡 * */ public static void four(int[] arr) { int temp =0; int low =0; int high = arr.length-1; int count =1;//躺数 while(low<high) { for(int i = low;i<high;i++) { //正向冒泡,确定最大值 if(arr[i] >arr[i+1]) { temp = arr[i+1]; arr[i+1] = arr[i]; arr[i] = temp; } } --high; //最后一个确定 for(int i = high ;i>low ;i--) { //确定最小值 if(arr[i] < arr[i-1]) { temp = arr[i+1]; arr[i+1] = arr[i]; arr[i] = temp; } } ++low;//第一个确定了 } } }
    天助自助者
  • 相关阅读:
    Python 面向对象
    pymysql增删改查
    pymysql简单链接示例
    mysql权限管理
    mysql五补充部分:SQL逻辑查询语句执行顺序
    mysql安装与基本管理
    mysql索引原理与慢查询优化2
    ftp 服务
    Linux 并发链接数
    Linux
  • 原文地址:https://www.cnblogs.com/ZeGod/p/9969525.html
Copyright © 2011-2022 走看看