使用quicksort

时间:2013-02-28 15:56:13

标签: java quicksort pseudocode

我正在从我的数据结构和算法书中进行快速排序。在书中,它列出了一个快速排序方法,然后是一个它希望您使用快速排序的分区分区。我好像有一个问题,我的hoare分区使用数组上的超出数字。要么使用8,要么我尝试修复它为-1。我是否正确地将书籍伪转换为java?

Quicksort伪代码

QuickSort(A, p, r)
if p<r
    q = partition(A, p, r);
    QuickSort(A, p, q - 1);
    QuickSort(A, q, r);

Hoare-Partition Pseudo Code

Hoare-Partition(A,p,r)
    x= A[p]
    i = p-1
    j=r+1
    while true
        repeat
            j=j-1
        until A [j] <= x
        repeat
            i = i +1
        until A[i] >= x
        if i < l
           exchange A[i] with A[j]
        else return j

我的代码

public class RunSort {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int[] sortNumbers = {4,5,6,2,3,7,2,1};
        int[] sorted = new int[sortNumbers.length];

        sorted = QuickSort(sortNumbers, 1, sortNumbers.length);
        System.out.print(sorted);
    }

    public static int[] QuickSort(int[] A, int p, int r){
        if(p < r){
            int q = partition(A, p, r);
            QuickSort(A, p, q - 1);
            QuickSort(A, q, r);
        }
        return A;

    }

    public static int partition(int[] A, int p, int r){
        int x = A[p];
        int i = p - 1;
        int j = r + 1;
        int temp;

        while(true){
            while(A[j] <= x && j != 0){
                j--;
            }
            while(A[i] >= x && i != A.length){
                i++;
            }
            if(i < j){
                temp = A[i];
                A[i] = A[j];
                A[j] = temp;
            }else{
                return j;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

提示:repeat {...} until (condition)while (condition) {...}的功能不同。

答案 1 :(得分:0)

根据文本的不同,伪代码通常使用1..arrayLength作为数组的索引边界,但在Java等中,它是0..arrayLength-1。您需要在QuickSort中调整主main来电的参数。

(作为一个挑剔,QuickSort应按惯例以小写字母开头。)