我很难将QuickSort与Hoare分区转换为C代码,但无法找到原因.我正在使用的代码如下所示:
void QuickSort(int a[],int start,int end) {
int q=HoarePartition(a,start,end);
if (end<=start) return;
QuickSort(a,q+1,end);
QuickSort(a,start,q);
}
int HoarePartition (int a[],int p, int r) {
int x=a[p],i=p-1,j=r;
while (1) {
do j--; while (a[j] > x);
do i++; while (a[i] < x);
if (i < j)
swap(&a[i],&a[j]);
else
return j;
}
}
Run Code Online (Sandbox Code Playgroud)
此外,我真的不明白为什么HoarePartition工作.有人可以解释它为什么有效,或者至少把我链接到一篇文章吗?
我已经看到了分区算法的逐步完成,但我没有直观的感觉.在我的代码中,它似乎甚至没有用.例如,给定数组
13 19 9 5 12 8 7 4 11 2 6 21
Run Code Online (Sandbox Code Playgroud)
它将使用数据透视表13,但最终会使用数组
6 2 9 5 12 8 7 4 11 19 13 21
Run Code Online (Sandbox Code Playgroud)
并将返回 …