其他分享
首页 > 其他分享> > 获取数组的前K小的元素

获取数组的前K小的元素

作者:互联网

//升序排列
template <typename Comparable>
int partition(vector<Comparable>& v, int left, int right) {
    if (left >= right) return left;
    int i = left, j = right;
    Comparable pivot = v[left];
    while (i < j) {
        while (i < j && !(v[j] < pivot)) j--;
        v[i] = v[j];
        while (i < j && v[i] < pivot) i++;
        v[j] = v[i];
    }
    v[i] = pivot;
    return i;
}

template <typename Comparable>
void getTopK(vector<Comparable>& v, int k) {
    int N = (int)v.size();
    if (N <= k) {
        return;
    }
    int left = 0;
    int right = N - 1;
    int mid = partition(v, left, right);
    //不断调整分治的位置,直到position = k-1
    //大了,往前调整
    //小了,往后调整
    while (mid != k - 1) {
        if (mid > k - 1) {
            right = mid - 1;
            mid = partition(v, left, right);
        } else {
            left = mid + 1;
            mid = partition(v, left, right);
        }
    }
    v.resize(k);
}

标签:right,int,元素,mid,partition,获取,数组,pivot,left
来源: https://www.cnblogs.com/txtp/p/16291559.html