Iterative Quicksort步骤?

时间:2015-08-25 05:51:25

标签: java iteration quicksort non-recursive

我必须在java中为家庭作业实现迭代快速排序。 我已经搜索了很多关于它但我找不到一个关于如何实现迭代快速排序的明确解释的网站。

我在java中找到了这个代码,它排序很好,但我不知道它是如何工作的,我知道递归快速排序是如何工作的。

我用我的问题评论了代码

public static void iterativeQsort(int[] arr) { 
    Stack<Integer> stack = new Stack<Integer>();
    stack.push(0);
    stack.push(arr.length);
    while (!stack.isEmpty()) {
        int end = stack.pop();
        int start = stack.pop();
        if (end - start < 2) continue;
        int p = start + ((end-start)/2);
        p = partition(arr,p,start,end); 

        stack.push(p+1);
        stack.push(end);

        stack.push(start);
        stack.push(p);

    }
}

private static int partition(int[] arr, int p, int start, int end) {
    int l = start;
    int h = end - 2; //what is h and l variables for and why h has to be end -2?
    int piv = arr[p];
    swap(arr,p,end-1);

    while (l < h) {
        if (arr[l] < piv) {
            l++;
        } else if (arr[h] >= piv) { 
            h--;
        } else { 
            swap(arr,l,h);
        }
    }
    int idx = h;  // what is idx exactly?
    if (arr[h] < piv) idx++;
    swap(arr,end-1,idx);
    return idx;  //why return idx.
}
private static void swap(int[] arr, int i, int j) { 
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

我对分区方法感到困惑,我不知道它的作用。

如果有人能解释我做出迭代快速排序的主要步骤,我会非常高兴。

感谢您的帮助。

0 个答案:

没有答案
相关问题