#include <iostream>
#include <stdlib.h> /* srand() , rand() */
#include <time.h>
using std::cout;
using std::endl;
int randomized_partition(int arr[], int p, int r)
{
srand(time(NULL));
int key = rand()%(r-p+1) + p, tmp = arr[key];
int i = p, j = r;
arr[key] = arr[p], arr[p] = tmp;
while (i < j)
{
// find the first element less than tmp from right
while (i < j && arr[j] > tmp)
--j;
if (i < j)
arr[i++] = arr[j];
// find the fist elment great than tmp from left
while (i < j && arr[i] < tmp)
++i;
if (i < j)
arr[j--] = arr[i];
}
arr[i] = tmp;
return i;
}
int randomized_select(int arr[], int p, int r, int i)
{
if (p == r)
return arr[p];
// partition randomly
int q = randomized_partition(arr, p, r);
int k = q - p + 1;
if (i == k)
return arr[q];
else if (i < k) // in the left
return randomized_select(arr, p, q-1, i);
else // in the right
return randomized_select(arr, q+1, r, i-k);
}
int main()
{
int arr[10] = {9, 0, 1, 5, 2, 8, 7, 6, 3, 4};
for (int i = 1; i <= 10; ++i)
cout << "i = " << i << " ---> "<< randomized_select(arr, 0, 9, i) << endl;
return 0;
}