intOrderStatistics(int*arr,int start,int end,int order){// k-th order statisticsint r =0;if(start == end){// Only 1 element in the arrayreturn arr[start];}
r =partition(arr, start, end);if(r == order){return arr[r];}elseif(order < r){returnOrderStatistics(arr, start, r -1, order);}else{returnOrderStatistics(arr, r +1, end, order);}}
1.2 划分函数
intpartition(int*arr,int start,int end){int midValue;int i = start;int j = start +1;srand(time(NULL));int random = start +rand()%(end - start +1);// printf("start is %d; end is %d; random is %d\r\n", start, end, random);swap(&arr[start],&arr[random]);
midValue = arr[start];for(;j <= end; j++){if(arr[j]<= midValue){
i++;swap(&arr[i],&arr[j]);}}swap(&arr[start],&arr[i]);return i;}
intmain(int argc,char*argv[]){test_printf(test,sizeof(test)/sizeof(int));int order =10;// index from 1 to ...int orderNum =OrderStatistics(test,0,sizeof(test)/sizeof(int)-1, order -1);printf("order %d number is %d\r\n", order, orderNum);return0;}
打印被测数组
voidtest_printf(int*arr,int len){int i =0;for(; i < len; i++){printf("|%6d", test[i]);if((i+1)%8==0){printf("|\r\n");}}if(i%8!=0){printf("|\r\n");}}