题目描述
输入n个数,求其中第k小的数。
输入要求
第一行包含两个整数n和k;n<1000,1<=K<=n
第二行包含n个整数。
输出要求
输出第k小的那个整数。
输入样例
15 1 1 3 7 2 4 6 -1 0 9 88 2 5 17 6 1
输出样例
-1
提示
可以通过此题学习分治法
#include<iostream>
#include <algorithm>
#include <stdio.h>
#include <cstdlib>
#include <time.h>
#include <stdlib.h>
using namespace std;
int a[1000];
int RandomizedPartition(int a[], int p, int r)
{
int i = (p+r)/2;
swap(a[i], a[p]);
int x = a[p];
int b = p, c = r + 1;
while (true)
{
while (a[++b]<x && b<r);
while (a[--c]>x);
if (b >= c) break;
swap(a[b], a[c]);
}
a[p] = a[c];
a[c] = x;
return c;
}
void QuickSort(int a[], int p, int r, int k)
{
if (p<r)
{
int q = RandomizedPartition(a, p, r);
if (k == q) return;
if (k<q)
QuickSort(a, p, q - 1,k);
if (k>q)
QuickSort(a, q + 1, r,k);
}
}
int main()
{
int n, k;
while (cin >> n >> k)
{
for (int i = 0; i<n; i++)
{
cin >> a[i];
}
QuickSort(a, 0, n - 1, k);
cout << a[k-1] << endl;
}
return 0;
}