快排递归和非递归(java)

思路:递归版思想没啥好说的,主要是细节,左右指针移动需要注意。这次尝试写非递归版,想的有点复杂了,其实类似树的前序遍历,细节见代码。

import javafx.util.Pair;
import java.util.Arrays;
import java.util.LinkedList;

public class Main {
    public static int[] nums = new int[]{2,8,7,4,9,3,1,6,5};
    //递归版快速排序
//    public static void quickSort(int left, int right){
//        while(left >= right - 1){
//            return;
//        }
//        int temp = nums[left];
//        int L = left, R = right - 1;
//        while(L <= R){
//            while(L < R && nums[R] >= temp){
//                R--;
//            }
//            if(L < R){
//                nums[L++] = nums[R];
//            }
//            while(L < R && nums[L] <= temp){
//                L++;
//            }
//            nums[R--] = nums[L];
//        }
//        nums[L] = temp;
//        quickSort(left, L);
//        quickSort(L+1, right);
//    }
    //非递归版快速排序
    public static void quickSortByStack(int left, int right){
        LinkedList<Pair> stack = new LinkedList<>();
        //保存左右边界
        stack.push(new Pair(left, right));
        while(!stack.isEmpty()){
            Pair pair = stack.pop();
            left = (int)pair.getKey();
            right = (int)pair.getValue();
            if(left >= right - 1){
                continue;
            }
            int temp = nums[left];
            int L = left, R = right - 1;
            //partition过程,注意细节
            while(L <= R){
                while(L < R && nums[R] >= temp){
                    R--;
                }
                if(L < R){
                    nums[L++] = nums[R];
                }
                while(L < R && nums[L] <= temp){
                    L++;
                }
                nums[R--] = nums[L];
            }
            nums[L] = temp;
            //先入右边部分,再入左边部分
            if(L < right - 1){
                stack.push(new Pair(L + 1, right));
            }
            if(left < L - 1){
                stack.push(new Pair(left, L));
            }
        }
    }
    public static void main(String[] args){
        System.out.println("before sort:");
        System.out.println(Arrays.toString(nums));

//        quickSortByStack(0, nums.length);
//        System.out.println("after qucik sort recursion:");
//        System.out.println(Arrays.toString(nums));

        quickSortByStack(0, nums.length);
        System.out.println("after qucik sort:");
        System.out.println(Arrays.toString(nums));
    }
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值