快速排序 递归&非递归 实现

递归实现

public class Test {
    public static void main(String[] args) {
        int[] arr = {19, 8, 27, 6, 315, 14, 99, 34, 27};
        quickSort(arr, 0, arr.length - 1);
        for(int i=0;i<arr.length;i++){
            System.out.println(arr[i]);
        }
    }
    
    public static void quickSort(int[] arr, int left, int right) {
        if (left >= right)
            return;
            
        int temp = arr[left];
        int i = left, j = right;
        while (i < j) {
            while (i < j && arr[j] >= temp) {
                j--;
            }
            while (i < j && arr[i] <= temp) {
                i++;
            }
            if (i < j) {
                int t = arr[i];
                arr[i] = arr[j];
                arr[j] = t;
            }
        }
        arr[left] = arr[i];
        arr[i] = temp;

        quickSort(arr, left, i-1);
        quickSort(arr, i+1, right);
    }
}

非递归实现

递归的算法主要是在划分子区间,如果要非递归实现快排,只要使用一个栈来保存区间就可以了。
一般将递归程序改成非递归首先应该想到的就是使用栈,因为递归本身就是一个压栈弹栈的过程。

public class Test {
    public static void main(String[] args) {
        int[] arr = {19, 8, 27, 6, 315, 14, 99, 34, 27};
        quickSortNotR(arr, 0 ,arr.length-1);
        for(int i:arr){
            System.out.println(i);
        }
    }
    
    public static void quickSortNotR(int[] arr, int left, int right) {
        if (left >= right)
            return;

        Stack<Integer> s = new Stack<>();
        s.push(left);
        s.push(right);  //后入的right,所以要先拿right
        while(!s.isEmpty())  //栈不为空
        {
            int r = s.pop();
            int l = s.pop();

            int index = partSort(arr,l,r);
            if((index - 1) > l)  //左子序列
            {
                s.push(l);
                s.push(index - 1);
            }
            if((index + 1) < r)  //右子序列
            {
                s.push(index + 1);
                s.push(r);
            }
        }
    }

	// 分区内排序,这部分和递归排序逻辑一样
    public static int partSort(int[] arr, int left, int right){
        int temp = arr[left];
        int i = left, j = right;
        while (i < j) {
            while (i < j && arr[j] >= temp) {
                j--;
            }
            while (i < j && arr[i] <= temp) {
                i++;
            }
            if (i < j) {
                int t = arr[i];
                arr[i] = arr[j];
                arr[j] = t;
            }
        }
        arr[left] = arr[i];
        arr[i] = temp;
        return i;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值