我目前正在开发一个程序,使用快速选择算法查找数组的第k个最小数目我已经完成了,而且很有效,但每次都没有给出正确的结果。
这是我的代码(我没有包括我的partition
或swap
算法,我确信它们是正确的):
/*
inputs...
*A: pointer to array
n: size of array
k: the item in question
*/
int ksmallest(int *A, int n, int k){
int left = 0;
int right = n - 1;
int next = 1;
return quickselect(A, left, right, k);
}
int quickselect(int *A, int left, int right, int k){
//p is position of pivot in the partitioned array
int p = partition(A, left, right);
//k equals pivot got lucky
if (p - 1 == k - 1){
return A[p];
}
//k less than pivot
else if (k - 1 < p - 1){
return quickselect(A, left, p - 1, k);
}
//k greater than pivot
else{
return quickselect(A, p + 1, right, k);
}
}
一切都很好然后我尝试在以下数组上使用该程序:
[1,3,8,2,4,9,7]
以下是我的研究结果:
> kthsm 2
4
> kthsm 1
1
> kthsm 3
2
如您所见,它在第1个最小的项目上工作正常,但在其他项目上失败有什么问题吗我猜我的索引没有了,但我不是很确定。
编辑:根据要求在下面添加了我的分区和交换代码:
int partition(int *A, int left, int right){
int pivot = A[right], i = left, x;
for (x = left; x < right - 1; x++){
if (A[x] <= pivot){
swap(&A[i], &A[x]);
i++;
}
}
swap(&A[i], &A[right]);
return i;
}
//Swaps
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}
最佳答案
在你的分区函数中,循环条件应该是x此外,在quickselect中的if语句中,您应该将p-1的两个用法都切换到p。p已经是一个索引,通过将k减少1,您也可以将它变成一个索引(而不是一个顺序)。没有必要再把p降低一次。
int partition(int *A, int left, int right){
int pivot = A[right], i = left, x;
for (x = left; x < right; x++){
if (A[x] < pivot){
swap(&A[i], &A[x]);
i++;
}
}
swap(&A[i], &A[right]);
return i;
}
int quickselect(int *A, int left, int right, int k){
//p is position of pivot in the partitioned array
int p = partition(A, left, right);
//k equals pivot got lucky
if (p == k-1){
return A[p];
}
//k less than pivot
else if (k - 1 < p){
return quickselect(A, left, p - 1, k);
}
//k greater than pivot
else{
return quickselect(A, p + 1, right, k);
}
}
这是一个有效的例子http://ideone.com/Bkaglb