#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int rand_select(int Arr[], int p, int q,int i);
int partition(int Arr[], int p, int q);
int main()
{
int arr[10] = { 10,50,4,7,8,20,6,3,2,1 };
for (int i = 0; i < 10; i++)
cout << arr[i] << endl;
int ith_samllest=rand_select(arr, 0, 9,6);
cout << "第六小的元素:" << ith_samllest <<endl;
return 0;
}
int rand_select(int Arr[], int p, int q, int i)
{
if (p == q)
{
return Arr[p];
}
int r = partition(Arr, p, q);
int k = r - p + 1;
if (i == k)
{
return Arr[r];
}
if (i < k)
{
return rand_select(Arr, p, r-1, i);
}
if (i > k)
{
return rand_select(Arr, r+1, q, i-k);
}
}
int partition(int Arr[], int p, int q)
{
int x = Arr[p];
int i = p;
for (int j = p + 1; j <= q; j++)
{
if (Arr[j] <= x)
{
i++;
swap(Arr[i], Arr[j]);
}
}
swap(Arr[p], Arr[i]);//不能把Arr[p]写成x;我也不知道为啥
return i;
}