将数组划分为两部分,一部分比某一值大,一部分比某一值小,在此基础上寻找第k小元素。(C语言实现)
#include <stdio.h> void swap(int m,int n){ int t=m; m=n; n=t; } int sort(int a[],int low,int high){ int p=a[low]; int s=low; int i; for(i=low;i<=high;i++){ if(a[i]<p){ s=s+1; swap(a[s],a[i]); } } swap(a[s],a[low]); return s; } int quicksort(int a[],int low,int high,int k){ if(low>high){ return -1; }else{ int base=sort(a,low,high); if(base+1==k){ return a[base]; }else if(base+1>k){ quicksort(a,low,base-1,k); }else{ quicksort(a,base+1,high,k); } } } int main(void) { int a[]={3, 16, 31, 43, 49, 51, 54, 56, 58, 68, 76, 67, 60, 87, 97}; int rs=quicksort(a,0,14,8); printf("%d\n",rs); return 0; }