快速排序的稳定版代码

    public void  quick(int[] nums,int l, int r){

        if(l >= r)return;

        int a = l,b = r;
        // 拷贝数组
        
        int[] copy = new int[r-l+1];
        int start = 0,end = copy.length-1;
        int e = r,s = l;

        int privot = nums[l];

        // 注意这里是 l<=r
        while (l <= r){
            while (l <= r && nums[r] >= privot){
                // 直接向后移动
                nums[e--] = nums[r--];
            }


            while (l <= r && nums[l] < privot){// 注意这里没有== 会将其移动到copy数组的左段
                // 直接向前移动
                nums[s++] = nums[l++];
            }
            if(l < r){
                // 大的移到copy数组右段
                copy[start++] = nums[l++];
                // 小的移动到copy数组的左段
                copy[end--] = nums[r--];

            }

        }

        // 把比privot小的复制
        // 将拷贝数组从左到右的复制
        for(int i = end+1; i <  copy.length; i++){
            nums[s++] = copy[i];
        }

        // 将把比privot大的复制
        for(int i = start-1 ; i >= 0 ;i--){
            nums[e--] = copy[i];
        }
//        System.out.println(privot == nums[s]);
        quick(nums,a,s-1);
        quick(nums,s+1,b);
    }
    public void  quick(int[] nums,int l, int r){

        if(l >= r)return;

        int a = l,b = r;
        // 拷贝数组

        int[] copy = new int[r-l+1];
        int start = 0,end = copy.length-1;
        int e = r,s = l;

        int privot = nums[l];

        // 注意这里是 l<=r
        while (l <= r){
            while (l <= r && nums[r] >= privot){
                // 直接向后移动
                nums[e--] = nums[r--];
            }


            while (l <= r && nums[l] < privot){// 注意这里没有== ,会将privot放到copy数组的第一个,因为此时进不了循环
                // 直接向前移动
                nums[s++] = nums[l++];
            }
            if(l < r){  // l==r  无需交换  该值无论>=privot还是<privot 都可以直接移动到num数组的前端或者后端   
                // 大的移到copy数组左段
                copy[start++] = nums[l++];
                // 小的移动到copy数组的右段
                copy[end--] = nums[r--];

            }

        }

        // 把比privot小的复制
        // 将拷贝数组从左到右的复制
        for(int i = end+1; i <  copy.length; i++){
            nums[s++] = copy[i];
        }

        int u = s; // 此时的s是prviot的所在的位置

        // 将把比privot大的复制
        for(int i = 0 ; i < start ;i++){
            nums[s++] = copy[i];
        }
//        System.out.println(privot == nums[u]);
        quick(nums,a,u-1);
        quick(nums,u+1,b);
    }

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值