快速排序非递归算法(栈)

 快速排序非递归算法(栈)

import java.util.Stack;

//快速排序非递归
public class Test {

    //使用栈保留左右两个边界,退出条件是左边界大于等于右边界
    public static int[] quickSortUnRecur(int[] arr) {
        int len = arr.length;

        if (len < 2) {
            return arr;
        }

        Stack<Integer> stack = new Stack<>();
        stack.push(0);
        stack.push(len - 1);

        while (!stack.isEmpty()) {
            int right = stack.pop();
            int left = stack.pop();

            if (left >= right) {
                continue;
            }

            int pos = left - 1;
            int pivot = arr[right];

            for (int i = left; i <= right; i++) {
                if (arr[i] <= pivot) {
                    pos++;
                    int tmp = arr[pos];
                    arr[pos] = arr[i];
                    arr[i] = tmp;
                }
            }
            stack.push(left);
            stack.push(pos - 1);
            stack.push(pos + 1);
            stack.push(right);
        }
        return arr;
    }

    public static void main(String[] args) {

        int[] arr = quickSortUnRecur(new int[]{4, 2, 5, 6, 2, 7, 1, 9, 0});
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}

 

posted @ 2020-04-18 19:27  All_just_for_fun  阅读(465)  评论(0编辑  收藏  举报