问题
I am working to implement a Hoare partition into a quicksort. I am trying to completely understand the hoare partition but the book doesnt explain everything. Mainly I am just wondering what the while TRUE part means? The excerpt from the book is below. If I were to put the while part in java what would I use and why?
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
回答1:
try this code for the algo that you have above :
int HoarePartition (int a[],int p, int r)
{
int x=a[p],i=p-1,j=r+1;
while (true)
{
while (a[j] <= x) j--;
while (a[i] >= x) i++;
if (i < j) swap(a[i],a[j]);
else return j;
}
}
回答2:
Here's a working translation:
public static void quicksort(int[] ar) {
if (ar == null) return;
quicksort(ar, 0, ar.length-1);
}
private static void quicksort(int[] ar, int lo, int hi) {
if (lo < hi) {
int splitPoint = partition(ar, lo, hi);
quicksort(ar, lo, splitPoint);
quicksort(ar, splitPoint+1, hi);
}
}
private static int partition(int[] ar, int lo, int hi) {
int pivot = ar[lo];
int i = lo-1, j = hi+1;
while(true) {
do { i++; } while(ar[i] < pivot);
do { j--; } while(ar[j] > pivot);
if (i < j) swap(ar, i, j);
else return j;
}
}
private static void swap(int[] ar, int i, int j) {
int tmp = ar[i];
ar[i] = ar[j];
ar[j] = tmp;
}
来源:https://stackoverflow.com/questions/15127540/hoare-partition-correctness-in-java