寻找数组中第k小(大)的元素

in C/C++ with 0 comment

#include "iostream"
#define NUM 100
using namespace std;

int a[13]={1,4,5,6,3,16,8,9,11,13,26,15,36,};
int select(int left,int right,int k){
	if(left>=right)
		return a[left];

		
		int p=a[left];
		int i=left;
		int j=right+1;
		while(i<j){
			i=i+1;
			while(a[i]<p){
				i=i+1;
			}
			j=j-1;
			while(a[j]>p){
				j=j-1;
			}
			if(i<j)
			swap(a[i],a[j]);
		}
		if(j-left+1==k)
			return p;
		a[left]=a[j];
		a[j]=p;
		if(j-left+1<k)
			return select(j+1,right,k-left-1);
		else return select(left,j-1,k);
}

int main(){
	int x=select(0,12,5);
	for(int i=0;i<13;i++)
		cout<<a[i]<<" ";
	cout<<"中,第5小的数是:"<<x<<endl;

	return 0;
}