#include <iostream> using namespace std; int arr[8]={4,5,1,6,2,7,3,8}; void Swap(int &a,int &b) { int temp=a; a=b; b=temp; } int Partion(int *array,int length,int low,int high) { while (low <high) { while(low<high && array[high]>=array[low]) high--; Swap(array[high],arr[low]); while(low < high && array[low]<=array[high]) low++; Swap(array[low],array[high]); } return low; } int GetLeastNumbers(int *input,int *output,int k,int length) { if(NULL==input ||NULL==output || length<=0 || k>length || k<=0) return 0; int low=0; int high=length-1; int index=Partion(input,length,low,high); while(index!=k-1) { if(index>k) { high=index-1; index=Partion(input,length,low,high); } else { low=index+1; index=Partion(input,length,low,high); } } for(int i=0;i<k;i++) output[i]=input[i]; } int main() { int *result=new int[4]; GetLeastNumbers(arr,result,4,8); cout<<"最小的4个数是:"; for(int i=0;i<4;i++) cout<<result[i]<<" "; delete []result; cout<<endl; system("pause"); return 0; }
运行结果为:
方案三实现代码:#include <iostream> #include <vector> #include <set> using namespace std; int arr[8]={4,5,1,6,2,7,3,8}; vector<int > v1(arr,arr+8); vector<int>::iterator it; multiset<int,greater<int>> intSet; multiset<int,greater<int>>::iterator itset; //这个对象里面存贮的元素是从小到大排序的,(因为用std::less作为比较工具); //如果是最大的元素:则是std::greater int GetLeastNumbers(const vector<int> & vec,multiset<int,greater<int>> &leastNumbers,int k) { leastNumbers.clear(); if( k<=0|| vec.size()<k) return 0; vector<int>::const_iterator it1=vec.begin(); for(;it1!=vec.end();it1++) { if(leastNumbers.size()<k) leastNumbers.insert(*it1); else { itset=leastNumbers.begin(); if(*it1<*(leastNumbers.begin())) { leastNumbers.erase(itset); leastNumbers.insert(*it1); } } } } int main() { int i=0; GetLeastNumbers(v1,intSet,4); cout<<"原数据:"; for(it=v1.begin();it!=v1.end();it++) cout<<*it<<" "; cout<<endl<<"前4小的数据:"; for(itset=intSet.begin();itset!=intSet.end();itset++) cout<<*itset<<" "; cout<<endl; system("pause"); return 0; }
运行结果: