我正在从我的《数据结构和算法》一书中进行快速排序。在书中,它列出了一个快速排序方法,然后列出了它希望您与快速排序一起使用的hoare分区。我似乎遇到了一个问题,我的hoare分区在数组上使用了越界的数字。它要么使用8,要么如果我尝试修复它,它将变为-1。我是否正确地将图书伪转换为java?
快速排序伪码
QuickSort(A, p, r)
if p<r
q = partition(A, p, r);
QuickSort(A, p, q - 1);
QuickSort(A, q, r);Hoare-Partition伪码
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;
}
}
}
}发布于 2013-02-28 23:59:35
提示:与while (condition) {...}不同,repeat {...} until (condition)不做同样的事情。
发布于 2013-03-01 00:08:00
根据文本的不同,伪代码通常使用1..arrayLength作为数组的索引边界,但在Java等人中,它是0..arrayLength-1。您需要在main中调整主QuickSort调用的参数。
(按照惯例,QuickSort应该以小写字母开头。)
https://stackoverflow.com/questions/15139930
复制相似问题