#include<stdio.h>
//交换两个元素
void swap(int *a, int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
//三数取中
void median3(int a[], int left, int right){
int middle = (left+right)/2;
if(a[left]>a[middle])
swap(&a[left], &a[middle]);
if(a[left]>a[right])
swap(&a[left], &a[right]);
if(a[middle]>a[right])
swap(&a[middle],&a[right]);
swap(&a[left], &a[middle]);
}
//划分(快速排序思想)
int partition(int a[], int left, int right){
if(left<=right){
int i = left;
int j = right;
int temp = a[left];
while(i<j){
while(i<j&&a[j]>temp){
j--;
}
swap(&a[i], &a[j]);
while(i<j && a[i]<temp)
i++;
swap(&a[i], &a[j]);
}
a[i] = temp;
return i;
}
}
//快速选择算法
int quickSelecting(int a[], int left, int right, int k){
if(left<=right){
median3(a, left, right);
int position = partition(a,left,right);
if(k-1 == position)
return a[position];
else if(k-1 < position)
quickSelecting(a,left,position-1,k);
else if(k-1 > position)
quickSelecting(a,position+1,right,k);
}
}
int main(){
int a[10] = {8, 1, 4 ,9, 6, 3, 5, 2, 7, 0};
int k;
printf("input the value of k:\n");
scanf("%d",&k);
int result = quickSelecting(a,0,9,k);
printf("the result is %d\n",result);
return 1;
}