快速排序

[Algo] 快速排序

1. 经典随机快排

// 1. 经典随机快排
void swapByIndex(vector<int> &v, int x, int y)
{
    int tmp = v[x];
    v[x] = v[y];
    v[y] = tmp;
}
pair<int, int> partition(vector<int> &v, int left, int right, int x)
{
    int first = left, last = right, cur = left;
    while (cur <= last)
    {
        if (v[cur] < x) swapByIndex(v, cur++, first++);
        else if (v[cur] > x) swapByIndex(v, cur, last--);
        else cur++;
    }
    return make_pair(first, last);
}
void quickSort(vector<int> &v, int left, int right)
{
    if (left >= right) return;
    int x = v[rand() % (right - left + 1) + left];
    pair<int, int> p = partition(v, left, right, x);
    quickSort(v, left, p.first - 1);
    quickSort(v, p.second + 1, right);
}

2. 随机选择(第k大的数)

// 2. 第k大的数
int findTopK(vector<int> &v, int k)
{
    if (k <= 0 || k > v.size()) return -1;
    int index = v.size() - k;
    int left = 0, right = v.size() - 1;
    while (1)
    {
        int x = v[rand() % (right - left + 1) + left];
        pair<int, int> p = partition(v, left, right, x);
        if (p.first <= index && index <= p.second) return v[index];
        else if (index < p.first) right = p.first - 1;
        else left = p.second + 1;
    }
    return -1;
}
posted @ 2024-12-07 13:53  yaoguyuan  阅读(6)  评论(0编辑  收藏  举报