随机快排

思路

  1. 随机找数组中一个数做基准数;
  2. 经过一个partition操作,达到基准数左边的数都比它小,右边的数都比它大。以此固定基准数的位置;
  3. 基准数左侧部分递归做partition操作;
  4. 基准数右侧部分递归做partition操作;
  5. 递归的出口是只剩一个元素。

partition

功能:经过一系列比较交换后,使base基准数左边的数都比它小,右边的数都比它大
流程:

  1. 规定less下标的左边为小于base的区域,more下标的右边为大于base的区域
  2. 用index指针遍历元素,从数组的L遍历到R
  3. 遍历到的数小于base,less右移,less位置和index位置元素交换,index右移
  4. 遍历到的数等于base index右移
  5. 遍历到的数大于base,more左移,more位置与index位置元素交换,index不动

代码

	/**
     * 随机快排
     */
	public static void quickSort(int[] arr, int left, int right) {
        if (left >= right) {
            return;
        }
        int base = arr[new Random().nextInt(arr.length)];
        int[] cut = partition(arr, base, left, right);
        quickSort(arr, left, cut[0]);
        quickSort(arr, cut[1], right);
    }

    /**
     * partition,即荷兰国旗问题
     */
    public static int[] partition(int[] arr, int base, int left, int right) {
        int less = left - 1;
        int more = right + 1;
        int index = left;
        while (index < more) {
            if (arr[index] < base) {
                less++;
                exchange(arr, less, index);
                index++;
            } else if (arr[index] == base) {
                index++;
            } else {
                more--;
                exchange(arr, more, index);
            }
        }
        return new int[]{less, more};
    }

    public static void exchange(int[] arr, int minIndex, int index) {
        int temp = arr[minIndex];
        arr[minIndex] = arr[index];
        arr[index] = temp;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值