//查找最小的k个元素 //20110602 yhm #include
using namespace std; int partition(int a[], int start, int end) { int key = a[start]; int low = start,high = end; while(low < high) { while(a[high] > key && low < high) high--; a[low] = a[high]; while(a[low] <= key && low < high) low++; a[high] = a[low]; } a[low] = key; return low; } //查找数组a中的最小的k个元素,返回第k小的元素的位置 //length 是数组a的长度. int findPos(int a[], int start, int end, int k) { //if(NULL == a || iLength <= 0 || k > iLength) // return -1; int pos = partition(a, start, end); int iLength = pos - start + 1; if(iLength == k) return pos; else if(iLength > k) return findPos(a, start, pos - 1, k); else return findPos(a, pos+1, end, k - iLength); } int main() { int a[20],n,k,p,i; while(cin>>n) { for(i=0;i
>a[i]; cin>>k; p = findPos(a,0,n-1,k); cout<<"最小的"<
<<"个数是:"<
找一个数组中的前k小的元素
最新推荐文章于 2022-05-01 22:11:43 发布