#include<stdio.h>
#include<conio.h>
#define P(x) printf("%d\n",x);
int A[10];
void printarray()
{
for (int i = 0; i < 8; i++)
printf("%d ", A[i]);
printf("\n");
}
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int partition(int beg, int end)
{
int a = beg, pivot = A[beg], b = end;
while (a < b)
{
while (A[a] <=pivot) a++;
while (A[b] > pivot) b--;
if (a < b)
{
swap(&A[a], &A[b]);
a++;
b--;
}
}
A[beg] = A[b]; // restore the pivot to its original location
A[b] = pivot;
return b;
}
int Select(int start, int end, int key)
{
if (start == end)
return A[start];
int p = partition(start, end);
int k = p - start + 1; // no of elements to the left of the pivot
if (key <= k)
return Select(start, k, key); // left
else
return Select(k+1, end, key-k);// right
}
}
int main()
{
// input being read from file
freopen("inp.txt", "r", stdin);
for (int i = 0; i < 10; i++)
{
scanf("%d", &A[i]);
}
P(A[Select(0, 7, 6)]);
getch();
return 0;
}
这里我使用了快速排序的分区功能对数组进行分区。我正在根据正在生成的枢轴和正在搜索的元素对分区的任一部分进行递归调用..即第 k 个最小的元素。