#include <iostream>
using namespace std;
int kth(int *arr, int l,int r,int k)
{
long long x = arr[(l+r) / 2];
int i=l,j=r;
while(i<=j)
{
while(arr[i] < x) i++;
while(arr[j] > x) j--;
if(i<=j)
{
std::swap(arr[i],arr[j]);
i++;
j--;
}
}
if(l<=k && k<=j)
return kth(arr, l,j,k);
if( i<=k && k<=r)
return kth(arr, i,r,k);
return arr[k];
}
int main() {
int a[4] = {3, 6, 4, 5};
cout << kth(a, 0, 4, 1) << endl;
cout << kth(a, 0, 4, 2) << endl;
cout << kth(a, 0, 4, 3) << endl;
cout << kth(a, 0, 4, 4) << endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwppbnQga3RoKGludCAqYXJyLCBpbnQgbCxpbnQgcixpbnQgaykKewogICAgbG9uZyBsb25nIHggPSBhcnJbKGwrcikgLyAyXTsKICAgIGludCBpPWwsaj1yOwogICAgd2hpbGUoaTw9aikKICAgIHsKICAgICAgICB3aGlsZShhcnJbaV0gPCB4KSBpKys7CiAgICAgICAgd2hpbGUoYXJyW2pdID4geCkgai0tOwoKICAgICAgICBpZihpPD1qKQogICAgICAgIHsKICAgICAgICAgICAgc3RkOjpzd2FwKGFycltpXSxhcnJbal0pOwogICAgICAgICAgICBpKys7CiAgICAgICAgICAgIGotLTsKICAgICAgICB9CiAgICB9CiAgICBpZihsPD1rICYmIGs8PWopCiAgICAgICAgcmV0dXJuIGt0aChhcnIsIGwsaixrKTsKICAgIGlmKCBpPD1rICYmIGs8PXIpCiAgICAgICAgcmV0dXJuIGt0aChhcnIsIGkscixrKTsKICAgIHJldHVybiBhcnJba107Cn0KCmludCBtYWluKCkgewoJaW50IGFbNF0gPSB7MywgNiwgNCwgNX07Cgljb3V0IDw8IGt0aChhLCAwLCA0LCAxKSA8PCBlbmRsOwoJY291dCA8PCBrdGgoYSwgMCwgNCwgMikgPDwgZW5kbDsKCWNvdXQgPDwga3RoKGEsIDAsIDQsIDMpIDw8IGVuZGw7Cgljb3V0IDw8IGt0aChhLCAwLCA0LCA0KSA8PCBlbmRsOwoJcmV0dXJuIDA7Cn0=