1.问题
n(1≤n≤100)个正整数(无序的)中,找出第k(k≤n)小的数。注意,第k小的数意味着从小到大排在第k位置的数。
2.解析
3.设计
int select(int a[],int start,int end,int k){
int m = 0;//记录有几组,每五个为一组;
int s[MAX];//用于保存每组的中位数;
int i = start;
while(i <= end){//对数组进行分组
int iend = i + 4;
if(iend >= end){
iend = end;
}
quickSort(a,i,iend);//对每组进行快速排序
s[m] = a[(i + iend)/2];//将每组的中位数记录下来
m++;
i = iend + 1;
}
quickSort(s,0,m-1);//对中位数进行排序
int mid = s[m/2];
int al[MAX],ar[MAX];
int count_al=0,count_ar=0;
for(int j=start;j<=end;j++){
if(a[j] < mid){
al[count_al++] = a[j];
}
else if(a[j] > mid){
ar[count_ar++] = a[j];
}
}
if(k == count_al + 1){
return mid;
}
else if(k <= count_al){
return select(al,0,count_al - 1,k);
}
else{
return select(ar,0,count_ar - 1,k-count_al -1);
}
}
4.分析
5.源码
[github源码地址]
https://github.com/henryzhang6686/myAlgorithmCode