在一个数组中找出top K的数

这个基本都是老生常谈了,看数据量有多大,建一个小根堆,或者用快速排序的方法来完成这个题。下面给出快速排序的方法,直接上代码了。

#include 
#include 
#include 

void quicksort(int arr[], int low, int high)
{
    if (low >= high)
        return;
    int i = low;
    int j = high;
    int val = arr[j];
    while (i < j)
    {
        while (i < j && arr[i] >= val)
            i++;
        arr[j] = arr[i];
        while (i < j && arr[j] < val)
            j--;
        arr[i] = arr[j];
    }
    arr[i] = val;
    quicksort(arr, low, i-1);
    quicksort(arr, i+1, high);
}

int quickselect(int arr[], int low, int high, int k)
{
    if (low >= high || k < low || k > high)
        return -1;
    int i = low;
    int j = high;
    int val = arr[j];
    while (i < j)
    {
        while (i < j && arr[i] >= val)
            i++;
        arr[j] = arr[i];
        while (i < j && arr[j] < val)
            j--;
        arr[i] = arr[j];
    }
    arr[i] = val;
    if (i == k || i == k+1) {
        return 0;
    } else if (i < k) {
        return quickselect(arr, i+1, high, k);
    } else {
        return quickselect(arr, low, i-1, k);
    }
    return 0;
}

int main(int argc, char *argv[])
{
    int arr[] = {23, -10, 102, 178, -101, 45, 9, 10, -27, 202, -353};
    int len = sizeof(arr)/sizeof(int);
    int i = 0;
    std::cout << "org data:" << std::endl;
    for (i = 0; i < len; i++)
        std::cout << arr[i] << " ";
    std::cout << std::endl;

    /*
    quicksort(arr, 0, len-1);
    std::cout << "sorted data:" << std::endl;
    for (i = 0; i < len; i++)
        std::cout << arr[i] << " ";
    std::cout << std::endl;
    */
    int K = 5;
    quickselect(arr, 0, len-1, K-1);
    std::cout << "top K data:" << std::endl;
    for (i = 0; i < len; i++)
        std::cout << arr[i] << " ";
    std::cout << std::endl;

    return 0;
}

你可能感兴趣的:(基础学习-C++)