Concept:

顺序统计量(order statistic):一个集合中按照大小顺序排列的位数。

Tips:

1、对集合进行快速排序。

2、将要求的第k位顺序统计量和第一步得到的pivot在数组中的位置相比较,如果相等,则pivot就是第K位的值,否则根据比较结果进行递归。

 

 

首先,快速排序partition代码:

Partition
 1 /*
2 Input:an array,and its number of elements.
3 Functioning:Quick sort this array by arr[0] as pivot
4 Output:the new position of pivot
5
6 */
7 int Partition(int* arr,int l,int r)
8 {
9 int pivot=arr[l];
10 int pos;
11 int left=l,right=r;
12 while(left<right)
13 {
14 while(left<right&&arr[right]>=pivot)
15 right--;
16 arr[left]=arr[right];
17 while(left<right&&arr[left]<=pivot)
18 left++;
19 arr[right]=arr[left];
20 }
21 arr[left]=pivot;
22 pos=left;
23
24 return pos;
25 }

然后,得到第k个顺序统计量值的代码:

Selection_N
 1 /*
2 Input:array,its number of elements,and the k-th order statistic
3 Functioning:Make a quick sort first,if the pivot's position equals k,then return the pivot.
4 Otherwise,recursion depends on the comparison between pivot's position and k.
5 Output:the k-th order value of this array.
6 */
7 int Select_N(int* arr,int l,int r,int k)
8 {
9 if(l==r)
10 return arr[l];
11 int pos=Partition(arr,l,r);
12 int i=pos-l+1;
13 if(i==k)
14 return arr[i];
15 else if(i>k)
16 return Select_N(arr,l,pos-1,k);
17 else
18 return Select_N(arr,pos+1,r,k-i);
19 }

最后,测试主程序

Main
 1 int main()
2 {
3 int n;
4 int k;
5 cout <<"Enter the number of array and the order you wanna search:";
6 cin >>n>>k;
7 int* a=new int[n];
8 cout <<"Enter the elements of array:";
9 for(int i=0;i<n;++i)
10 cin >>a[i];
11
12 int value=Select_N(a,0,n-1,k);
13 cout <<"The"<<k<<"th order of this array is "<<value<<endl;
14 for(int i=0;i<n;++i)
15 cout <<a[i]<<endl;
16
17 system("pause");
18
19 return 0;
20 }

 


PS:今天写了个Select_N的迭代版本,代码如下:

Selection_N
 1 int Select_N(int* arr,int l,int r,int k)
2 {
3 while(l<r)
4 {
5 int pos=Partition(arr,l,r)-l+1;
6 if(pos==k)
7 return arr[pos];
8 else if(pos<k)
9 {
10 l=pos+1;
11 k=k-pos;
12 }
13 else
14 {
15 r=pos-1;
16 }
17 }
18 return arr[l];
19 }




 

相关文章: