首页 > 代码库 > 快排查找第K小的数

快排查找第K小的数

#include "iostream.h"
using namespace std;
int findMedian(int *A,int left,int right){
	int center = (left+right)/2;
	if(A[left]>A[center]){
		swap(A[left],A[center]);
	}
	if(A[left]>A[right]){
		swap(A[left],A[right]);
	}
	if(A[center]>A[right]){
		swap(A[center],A[right]);
	}
	//A[right]已经大于A[center] 
	swap(A[center],A[right-1]);
	return A[right-1];
	
}
void insertSort(int *A, int left,int right){
	
	for(int i=left+1;i<=right;i++){
		int p = A[i];
		int j;
		for( j=i;j>=left&&A[j-1]>p;j--){
			A[j]=A[j-1];
		}
		A[j]=p;
	}
}
#define CUTOFF 5
int qselect(int *A, int k, int left,int right){
	if(left+CUTOFF<right){
		int pivot = findMedian(A,left,right);
		
		int i=left;
		int j=right-1;
		for(;;){
			while(A[++i]<pivot){}
			while(A[--j]>pivot){}
			if(i<j){
				//此时A[i]>=pivot&&A[j]<=pivot,交换二者位置 
				swap(A[i],A[j]);
			}else
			    break;
		}
		swap(A[i],A[right-1]);
		int t = i-left+1;
		if(k==t)
		    return A[i];
	    else if(k<t){
	    	return qselect(A,k,left,i-1);
	    }else{
	    	return qselect(A,k-t,i+1,right);
	    }
    }else{
    	insertSort(A,left,right);
    	return A[k+left-1];
    }
}
int main()
{
	int A[100];
	int N;
	cin>>N;
	for(int i=0;i<N;i++){
		cin>>A[i];
	}
	int k;
	cin>>k;
	
	if(k<=N-0)
	    cout<<qselect(A,k,0,N-1)<<endl;
	return 0;
}

快排查找第K小的数