//时间复杂度:
//T(n) = T(n/2) + f(n)
//f(n)即为partition(),时间复杂度o(n)
//由主定理可知a=1,b=2
//log b a < 1
//符合主定理第三种情况
//因此由o(T(n))=o(f(n)) = o(n)
#include <iostream>
using namespace std;
int* partition(int* start,int* end){
int* i = start;
int* j = end;
int key = *start;
while(i<j) {
while(*j>=key && i<j) {
j--;
}
if(j == i)
break;
*i = *j;
i++;
while(*i<=key && i < j) {
i++;
}
if(j == i)
break;
*j = *i;
j--;
}
*i = key;
return i;
}
int* select(int* start,int* end,int k) {
if(k < 1 || k > end - start + 1)
return NULL;
if(start == end)
return start;
int* i = partition(start,end);
if(i- start + 1 > k) {
return select(start,i-1,k);
} else if(i -start +1 == k) {
return i;
} else {
return select(i+1,end,k-(i-start+1));
}
}
int main(){
int num[] = {4,5,3,7,55,3,6};
int* ret = select(num,num+6,7);
if(ret)
cout<<*ret<<endl;
else cout<<"Not Found!"<<endl;
}
o(n)时间寻找第k小的数
最新推荐文章于 2023-06-19 23:14:38 发布