搜索第k元
#include<stdio.h>
#pragma warning (disabled:4996)
int Search(int A[],int n,int k)
{
int i;
if(k>=n)
return -1;
else
{
i=Partition(A,n);//indirect recursion
if(i==k)
return i;
else if(i>k)
return Search(A,i,k);
else
return Search(A+i+1,n-i-1,k-i-1);
}
}
int Partition(int A[],int n)
{//长短比例小于1:3的Partition,return the position of the pivot
int low,high,x,p,i,v;
if(n<25){//当n<25时,作为递归起点,直接获得中间元素作为主元
BubbleSort(A,n);
return n/2;
}
else{
for(i=0;i<n/5;i++){//每5个元素作为一组
BubbleSort(A+i*5,5);//采用BubbleSort
v=A[i*5+2];
A[i+5+2]=A[i];
A[i]=v;
}
x=Search(A,n/5,n/10);//indirect recursion
p=A[x];
A[x]=A[0];
x=0;
low=0;//low pointer
high=n-1;//high pointer
while(low<high){//指针从两头相对扫描,直到相遇
while(low<high&&A[high]>p)//从后向前寻找比主元p小的元素
high--;
if(low<high){//A[high]<=p
A[x]=A[high];
x=high;
}
while(low<high&&A[low]<=p)//从前向后寻找比主元pivot大的元素
low++;
if(low<high){//A[low]>p
A[x]=A[low];
x=low;
}
}
A[x]=p;
return x;
}
}
int BubbleSort(int A[],int n)
{
int i,j,x;
for(int i=0;i++;i<n-1)
for(int j=0;j++;j<n-i-1)
if(A[j]<A[j+1])
{
x=A[j];
A[j]=A[j+1];
A[j+1]=x;
}
return 1;
}