According to the preceding solution of programming, similar to the division method of fast sorting, N numbers are stored in array s, and then a random number X is selected from the array, divide the array into two parts: SA and SB. Sa <= x <= sb. If the k elements to be searched are smaller than the number of SA elements, return the smaller k elements in SA; otherwise, return the smaller K-| sa | elements in SA + sb. Continue recursion and break down the problem into smaller ones,The average time complexity is O (n)
// Copyright 2012 Jike Inc. All Rights Reserved.// Author: jichenghui@jike.com(Chenghui Ji)// Date : 2012-08-24 16:35:51// Brief : #include <iostream>using namespace std;int partition(int* data, int left, int right) { if (left > right) { return -1; } else { int polit = data[left]; while(left < right) { while(right > left && data[right] >= polit) right--; data[left] = data[right]; while (left < right && data[left] <= polit) left++; data[right] = data[left]; } data[left] = polit; } return left;}void topk_qsort(int* data, int left, int right, int k) { if (left >= right || k > right - left + 1) { return; } int polit = partition(data, left, right); if (polit < left || polit >= right) return; int left_len = polit - left + 1; if (left_len == k) return; else if (left_len > k) { topk_qsort(data, left, polit-1, k); } else { topk_qsort(data, polit + 1, right, k - left_len); }}int main() { int data[] = {13,2,3,5,67,8,9,10,17,6}; int len = sizeof(data)/sizeof(data[0]); cout << "orignal data:" << endl; for (int i = 0; i < len; ++i) { cout << data[i] << " "; } cout << endl; int k = 3; cout << "top" << k << "data:" << endl; topk_qsort(data, 0, len-1, k); for (int i = 0; i < len; ++i) { cout << data[i] << " "; } cout << endl; return 0;}