寻找第n大的数 o(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<iostream>
#include<cstdlib>
#include<ctime>
using std::endl;
using std::cin;
using std::cout;
int partition(int *a,int l,int r);
int select(int *a,int l,int r,int i);
void swap(int *a,int i,int j);
int main(){
srand(time(0));
int count;
cout<<"请输入数组个数:";
cin>>count;
int *a = new int[count];
cout<<"请输入数组:";
for(int i = 0;i<count;i++)
cin>>a[i];
cout<<"请输入希望寻找第几大的数:";
int ch;
cin>>ch;
cout<<"it is :"<<select(a,0,count-1,ch);
cout<<endl;
return 0;
}
int select(int *a ,int l,int r,int i){
int re = partition(a,l,r);
if(r == l)
return a[r];
if(re -l+1 >= i){
select(a,l,re,i);
}else{
select(a,re+1,r,i-(re-l+1));
}
}
void swap(int *a,int i,int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
int partition(int *a,int l,int r){
if((l-r)==0)
return l;
int m = l+rand()%(r-l);
swap(a,m,r);
int left = l-1;
int right = l-1;
while(++right < r){
if(a[right] < a[r]){
swap(a,right,++left);
}
}
swap(a,left+1,r);
return left+1;
}