简体   繁体   English

在数组中找到第K个最大的整数

[英]Find the Kth largest int in array

I am trying to use quickselect in c++ to do this, but it keeps returning me the kth smallest element instead of the kth largest. 我正在尝试在c ++中使用quickselect来执行此操作,但是它一直使我返回第k个最小的元素,而不是第k个最大的元素。 Where is my logic wrong? 我的逻辑错在哪里?

int partition(int* input, int p, int r)
{
    int pivot = input[r];

    while ( p < r )
    {
        while ( input[p] < pivot )
            p++;

        while ( input[r] > pivot )
            r--;

        if ( input[p] == input[r] )
            p++;
        else if ( p < r ) {
            int tmp = input[p];
            input[p] = input[r];
            input[r] = tmp;
        }
    }

    return r;
}

int quick_select(int* input, int p, int r, int k)
{
    if ( p == r ) return input[p];
    int j = partition(input, p, r);
    int length = j - p + 1;
    if ( length == k ) return input[j];
    else if ( k < length ) return quick_select(input, p, j - 1, k);
    else  return quick_select(input, j + 1, r, k - length);
}

What should I change to make this kth largest instead of kth smallest element? 我应该怎么做才能使第k个最大元素代替第k个最小元素?

the < and > in your code is reverse in partition() as @Dietmar Kühl mentioned,by change them,it works correctly. 如@DietmarKühl所述,代码中的<>partition()是相反的,通过更改它们,它可以正常工作。

besides,my suggestion is to use a normal partition() of quicksort as follow, for whose two index of which move in the same direction and one of them never surpasses another. 此外,我的建议是使用快速排序的普通partition() ,其两个索引沿相同方向移动,并且其中一个索引永远不会超过另一个索引。 It is not easy to make anyone confused. 使任何人感到困惑都不容易。

int partition(int *input, int p, int r) {
    int pivot,i,j,tmp;
    pivot = input[r];
    i = p-1;
    for (j=p;j<=r-1;j++) {
        if (input[j]>= pivot) {
            i++;
        tmp = input[i];
        input[i] = input[j];
        input[j] = tmp;
        }
    }
    tmp = input[i+1];   
    input[i+1] = input[r];
    input[r] = tmp;
    return i+1;
}

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

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