Idea: Use the fast sort patition function to process time complexity O (n) #include <iostream> #include <cassert>using namespace Std;int partition (int *ar, int len, int low, int.) {int temp = Ar[low];while (Low < High) {while (Low < high && temp < Ar[high]) {high--;} if (low = = high) {break;} Else{ar[low] = Ar[high];} while (Low < high && temp > Ar[low]) {low++;} if (low = = high) {break;} Else{ar[high] = Ar[low];}} Ar[low] = Temp;return low;} int findkmin (int *ar, int len, int k)//Search for K small number {assert ((ar!=null) && (k>0) && (k<len+1)); int low = 0;int = Len-1;int index = partition (AR, Len, Low, high) and while (Index! = k-1) {if (Index > k) {index = partition (AR, Len, Low, index-1);} Else{index = partition (AR, Len, index+1, High);}} return Ar[index];} void findkmin (int *ar, int len, int k, int *retar)//Find the smallest number of K {assert (Ar!=null) && (k>0) && (k<len+1 ) && (retar!=null)); int low = 0;int High = Len-1;int index = partition (AR, Len, Low, high) and while (IndeX! = k-1) {if (Index > k) {index = partition (AR, Len, Low, index-1);} Else{index = partition (AR, Len, index+1, High);}} for (int i = 0; i<=index; ++i) {retar[i] = Ar[i];}} void Show (int *ar, int len) {for (int i=0; i<len; ++i) {cout<<ar[i]<< "";} Cout<<endl;} int main () {int ar[] = {7,3,5,6,4,1,2};int Retar[32];int len = sizeof (AR)/sizeof (ar[0]); int len2 = sizeof (Retar)/sizeof (re Tar[0]); Cout<<findkmin (AR, Len, 7) <<endl;cout<<findkmin (AR, Len, 1) <<endl;cout<< Findkmin (AR, Len, 5) <<endl;//cout<<findkmin (AR, len, 0) <<endl;//cout<<findkmin (AR, Len, 8) <<endl;findkmin (AR, Len, 7, Retar), Show (Retar, 7), Findkmin (AR, Len, 1, Retar); Show (Retar, 1); Findkmin (AR, Len, 5, R Etar); Show (Retar, 5); return 0;}
O (n) time complexity for the smallest number of K and K small