繁体   English   中英

我的quickselect算法未返回正确的值

[英]My quickselect algorithm is not returning the correct value

因此,我试图在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)]));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM