所以我试图在C ++中实现一个quickselect算法,以便在向量中找到中值,但是它没有对列表进行适当的部分排序,也没有返回正确的中值。
我似乎无法找到错误的位置。我是这个算法的新手,这是我第一次尝试实现它。我已将我的代码包含在下面,所以如果有人比我更了解什么是错误的,我会非常感谢你的意见。
//Returns the index of the object with the kth largest value
int QuickSelect(vector<Object *> & list, int left, int right, int k){
/*-Base case-*/
if(left == right) /*List only contains a single element*/
return left; /*Return that index*/
int pivotIndex = left + (rand() % (int)(right - left + 1));
int pivotNewIndex = Partition(list, level, left, right, pivotIndex);
int pivotDist = pivotNewIndex - left + 1;
if(pivotDist == k)
return pivotNewIndex;
else if (k < pivotDist)
return QuickSelect(list, level, left, pivotNewIndex-1, k);
else
return QuickSelect(list, level, pivotNewIndex+1, right, k-pivotDist);
}
int Partition(vector<Object *> & list, int left, int right, int pivotIndex){
int pivotValue = list.at(pivotIndex)->value;
std::swap(list[pivotIndex], list[right]);
int storeIndex = left;
for(int i = left; i < right; i++){
if(list.at(i)->value < pivotValue){
std::swap(list[storeIndex], list[i]);
storeIndex++;
}
}
std::swap(list[right], list[storeIndex]);
return storeIndex;
}
答案 0 :(得分:0)
int pivotDist = pivotNewIndex - left + 1;
应该是
int pivotDist = pivotNewIndex - left;
另外
return QuickSelect(list, pivotNewIndex+1, right, k-pivotDist);
应该是
return QuickSelect(list, pivotNewIndex+1, right, k-pivotDist-1);
我的测试代码是:
int main() {
int d[] = {0, 1, 2, 3, 4};
do {
std::vector<Object*> v;
v.push_back(new Object(d[0]));
v.push_back(new Object(d[1]));
v.push_back(new Object(d[2]));
v.push_back(new Object(d[3]));
v.push_back(new Object(d[4]));
for (int i = 0; i < v.size(); ++i) {
std::cout << v[i]->value << " "; }
std::cout << std::endl;
int n = QuickSelect(v, 0, 4, 2);
if (v[n]->value != 2) {
std::cout << "error: ";
for (int i = 0; i < v.size(); ++i) {
std::cout << v[i]->value << " "; }
std::cout << std::endl;
}
}
while (std::next_permutation(&d[0], &d[sizeof(d)/sizeof(int)]));
}