#include "stdafx.h"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
void swap(int & a, int & b);
int find_position(int* a,int k, int low,int high);
int find_orderk(int* a, int k, int low,int high);
void swap(int & a, int & b)
{
int tmp = a;
a = b;
b = tmp;
}
int find_position(int* a,int k, int low,int high)
{
if (low >= high)
{
return low;
}
int m = rand() % (high - low) + low;
int tmp = a[m];
int p = m;
int lowpos = low;
bool bfindlow = false;
for (int i = low; i < m; i++)
{
if (a[i] >= tmp && bfindlow)
{
swap(a[lowpos++], a[i]);
}
else if(a[i] < tmp && !bfindlow)
{
lowpos = i;
bfindlow = true;
}
}
if (bfindlow)
{
swap(a[lowpos], a[m]);
p = lowpos;
}
int highpos = p;
lowpos = p+1;
bool bfindhigh = false;
for (int i = m+1; i <= high; i++)
{
if (a[i] >= tmp)
{
highpos = i;
if (!bfindhigh)
{
bfindhigh = true;
}
if(bfindlow)
{
highpos = lowpos;
swap(a[lowpos++], a[i]);
}
}
else
{
if(!bfindlow)
{
bfindlow = true;
lowpos = i;
}
}
}
if(bfindhigh)
{
swap(a[p], a[highpos]);
p = highpos;
}
return p;
}
int find_orderk(int* a, int k, int low,int high)
{
int p = find_position(a, k-1+low, low, high);
if(p-low < k-1)
{
p = find_orderk(a, (k-1)-(p-low), p+1, high);
}
else if (p-low > k-1)
{
p = find_orderk(a, k, low, p-1);
}
return p;
}
int main ()
{
srand((unsigned) time(NULL));
int k = 1;
while (k <= 10)
{
int a[10]={9,11,6,2,8,12,7,3,20,1};
int p = find_orderk(a, k, 0, 9);
printf("\n NO. %d VALUE : %d\n", k, a[p]);
k++;
}
return 0;
}