求出第k大的数,
这个好像我就遇到过,,,原来是用快排弄的,,诶,,
好像是快了点,,有的题目用到的思想真是让人捉摸不透呀...
贴出代码:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
using namespace std;
const int maxn = 11111;
int n;
int k;
int a[maxn];
int Solve(int low, int high)
{
if (low < high)
{
int pivot = a[low];
int i = low;
int j = high;
while (i < j)
{
while (i < j && a[j] >= pivot)
{
j--;
}
a[i] = a[j];
while (i < j && a[i] <= pivot)
{
i++;
}
a[j] = a[i];
}
a[i] = pivot;
int mid = i + (j - i) / 2;
if (i == k)
{
return pivot;
}
else
{
if (k <= mid)
{
return Solve(low, mid);
}
else
{
return Solve(mid + 1, high);
}
}
}
}
int main()
{
while (scanf("%d%d", &n, &k) != EOF)
{
for (int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
}
int ans = Solve(1, n);
printf("%d", ans);
cout << endl;
}
system("pause");
return 0;
}