#include <stdio.h>
#define CutOff (3) //截至范围
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void insert_sort(int arr[], int len)
{
for (int i = 1; i < len; i++)
{
int tmp = arr[i];
int j = i;
for (; j > 0 && arr[j - 1] > tmp; j--)
arr[j] = arr[j - 1];
arr[j] = tmp;
}
}
//设定枢纽元pivot
int median3(int arr[], int left, int right)
{
int center = (left + right) / 2;
if (arr[left] > arr[right])
swap(&arr[left], &arr[right]);
if (arr[center] > arr[right])
swap(&arr[center], &arr[right]);
if (arr[left] > arr[center])
swap(&arr[left], &arr[center]);
swap(&arr[center], &arr[right - 1]);
return arr[right - 1];
}
void select(int arr[], int k, int left, int right)
{
if (left + CutOff <= right)
{
int pivot = median3(arr, left, right);
int i = left;
int j = right - 1;
while (1)
{
while (arr[++i] < pivot)
;
while (arr[--j] > pivot)
;
if (i < j)
swap(&arr[i], &arr[j]);
else
break;
}
swap(&arr[i], &arr[right - 1]);
if (k > i)
select(arr, k, left, i - 1);
else if (k > i)
select(arr, k, i + 1, right);
else
return;
}
else
insert_sort(arr + left, right - left + 1);
}
int a[] = {12, 34, 2, 35, 5, 3, 10, 6, 7, 8};
int main()
{
int len = sizeof(a)/sizeof(a[0]);
int k = 5;
select(a, k, 0, len - 1);
printf("%d\n", a[k]);
}