我的快速选择算法未返回正确的值



所以我正在尝试在C++中实现快速选择算法,以便在向量中找到中值,但是它没有正确地对列表进行部分排序,也没有返回正确的中值。

我似乎找不到错误在哪里。我是这个算法的新手,这是我第一次尝试实现它。我在下面包含了我的代码,所以如果有人比我更有知识,对出了什么问题有任何想法,我将非常感谢您的意见。

//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;
}
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)]));
}

最新更新