和高速排序有点类似,利用高速排序的划分算法,
划分算法见http://blog.csdn.net/buyingfei8888/article/details/8997803
依据int partition(int number[],int start,int end);返回值为数组下标,大小为index,index左边值均小于number【index】,右边均大于number【index】,若为k-1.则左边值均为所求。
代码:
#include <iostream> using namespace std; int partition(int number[],int start,int end){ int temp=number[start]; while(start<end){ while(start<end && number[end]>temp) --end; if(start < end) number[start++] = number[end]; while(start<end && number[start]<temp) start++; if(start<end) number[end--] = number[start]; number[start]=temp; } return end; } void getLeastNumber(int * input,int start,int end,int * output,int k){ if(NULL == input || NULL == output || k <=0 || start <0 || end < 1) return ; int index=partition(input,start,end); while(index != k-1){ if(index > k-1){ end = index -1; index = partition(input,start,end); } if(index < k-1){ start = index + 1; index = partition(input , start , end ); } } for(int i=0;i<k;i++){ output[i] = input[i]; cout<< input[i]<<" "; } } int main(){ int input[8]={2,1,4,3,99,100,56,909}; int *output; getLeastNumber(input,0,7,output,7); return 0; }