三个基本排序

1.冒泡排序

简单冒泡排序,并且简单优化,减少遍历。

/**
 * 冒泡排序
 *
 * 两个之间比较 大的数向后移
 *
 * 乱序变成从小到大排序
 *
 */
public class Maopao {
    public static void main(String[] args) {
        int[] arr = {0,2,3,5,6,8,9,1,4,7};
        test(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] +" ");
        }
    }

    public static void test(int[] arr) {
        for (int j = 0; j <arr.length; j++) {

            boolean a = true;
            for (int i = 0; i < arr.length - 1 -j; i++) {
                if (arr[i] > arr[i + 1]) {
                    a = false;
                    int temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                }
            }
            //减少遍历次数 没有交换就跳出循环
            if (a) break;

            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] +" ");
            }
            System.out.println();
        }
    }
}

2.插入排序

/**
 * 插入排序
 *
 * 跟自身前面的每个数比较
 */
public class ChaRu {
    public static void main(String[] args) {
        int[] arr = {8,5,0,1,4,9,2,3,6,7};
        test(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] +" ");
        }
    }

    public static void test(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            int temp = arr[i];
            int j = i - 1;
            while (j>= 0 && temp < arr[j]){
                arr[j+1] = arr[j];
                j--;
            }
            arr[j+1] = temp;
            for (int a = 0; a < arr.length; a++) {
                System.out.print(arr[a] +" ");
            }
            System.out.println();
        }
    }
}

3.选择排序

/**
 * 选择排序
 *
 * 选择最小的排在前面
 */
public class XuanZe {
    public static void main(String[] args) {
        int[] arr = {8, 5, 0, 1, 4, 9, 2, 3, 6, 7};
        test(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }

    public static void test(int[] arr) {
        for (int i = 0; i < arr.length-1; i++) {
            int min = arr[i],pos = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < min){
                    min = arr[j];
                    pos = j;
                }
            }
            int temp = arr[i];
            arr[i] = arr[pos];
            arr[pos] = temp;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值