给定n个元素和1个k,1<=k<=n,要求找出这n个元素中第k小的元素。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
//快排
int Partition(int a[], int low, int high)
{
int i = low, j = high, pivot = a[low];
while (i < j)
{
while (i < j && a[i] <= pivot)
{
i++;
}
while (i < j && a[j] > pivot)
{
j--;
}
if (i < j)
{
swap(a[i++], a[j--]);
}
}
if (a[i] > pivot)
{
swap(a[i - 1], a[low]);
return i - 1;
}
swap(a[i], a[low]);
return i;
}
//利用随机数种子随机分配一个基准数
int RandomPartition(int a[], int low, int high)
{
srand(time(NULL));
int i = low + rand() % (high - low + 1);
swap(a[i], a[low]);
return Partition(a, low, high);
}
//线性时间选择核心算法
int RandomSelect(int a[], int low, int high, int k)
{
if (low == high)
{
return a[low];//找到该数
}
int i = RandomPartition(a, low, high);//随机分区
int j = i - low + 1;//区间长度,从low位置算起
if (j < k)
{
return RandomSelect(a, i + 1, high, k - j);//当前区间长度比k大,说明第k小的数在右区间
}
return RandomSelect(a, low, i, k);//当前区间长度比k小,说明第k小的数在左区间
}
int main()
{
int a[]={1, 2, 3, 4, 5, 6, 7, 8};
cout << RandomSelect(a, 0, 7, 6) << endl;
return 0;
}