题目:输入n个整数,找出其中的最小k个数。
代码示例:
#include<iostream>
#include<time.h>
using namespace std;
void SwapTwoNum(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
int Partion(int a[], int length, int start, int end)
{
if (a == NULL || length <= 0 || start > end)
throw "error";
srand((unsigned int)time(NULL));
int index = rand() % (end - start + 1) + start;
SwapTwoNum(a[index], a[end]);
int small = start - 1;
for (int index = start; index < end; index++)
{
if (a[index] < a[end])
{
small++;
if (small != index)
{
SwapTwoNum(a[small], a[index]);
}
}
}
small++;
SwapTwoNum(a[small], a[end]);
return small;
}
void FindKSmall(int a[], int length,int start,int end,int k)
{
if (a == NULL || length <= 0||k>length||start>end)
return;
int index = Partion(a, length, start, end);
while (index != k - 1)
{
if (index > k - 1)
{
index = Partion(a, length, start, index - 1);
}
else
{
index = Partion(a, length, index + 1, end);
}
}
}
int main()
{
const int n = 10;
int k = 5;
int a[n] = { 7, 3, 2, 6, 9, 0, 12, 10, 32, 5 };
cout << "原数组:";
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
cout << "最小的" << k << "个数:";
FindKSmall(a, n, 0, n - 1, k);
for (int i = 0; i < k; i++)
cout << a[i] << " ";
cout << endl;
}