#include<iostream>
using namespace std;
int Partition(int* arr, int low, int high)
{
int temp = arr[low];
while (low < high)
{
while (low < high && arr[high] >= temp)
high--;
arr[low] = arr[high];
while (low < high && arr[low] <= temp)
low++;
arr[high] = arr[low];
}
arr[low] = temp;
return low;
}
int KthElement(int* arr, int low, int high, int len, int k)
{
if (arr == nullptr || low >= high || k > len)
return 0;
int pos = Partition(arr, low, high);
while (pos != len - k)
{
if (pos > len - k)
{
high = pos - 1;
pos = Partition(arr, low, high);
}
if (pos < len - k)
{
low = pos + 1;
pos = Partition(arr, low, high);
}
}
return arr[pos];
}
int main()
{
int a1[] = { 1,3,5,7,88,11 };
cout << KthElement(a1, 0, 5, 6, 2)<<endl;
int a2[] = { 1,99,5,7,88,32 };
cout << KthElement(a2, 0, 5, 6, 1)<<endl;
int a3[] = { 1,99,5,7,88,16 };
cout << KthElement(a3, 0, 5, 6, 3) << endl;
}