#include <iostream>
#include <vector>
using namespace std;
int findKthLargest(vector<int>& nums, int k);
int main()
{
int a[6] = {3,2,1,5,6,4};
int b[] = {3,2,3,1,2,4,5,5,6};
int c[] = {1};
int d[] = {-1,2,0};
vector<int> nums(b,b + 9);
//cout << findKthLargest(nums,4);
vector<int> nums1(a,a + 6);
vector<int> nums2(d,d + 3);
cout << findKthLargest(nums2,1);
return 0;
}
int findKthLargest(vector<int>& nums, int k)
{
//if(nums.size() < k)return -1; //judge
k--;
int i = 0,j = nums.size() - 1;
while(true)
{
int ii = i,jj = j; //record the positions of i and j
cout << "ii:" << ii << " jj:" << jj << endl;
int key = nums[j];
while(i < j) //find the num[j]'s position in the final sequence
{
while(i < j && nums[i] >= key)i++;
nums[j] = nums[i];
while(i < j && nums[j] <= key)j--;
nums[i] = nums[j];
}
nums[i] = key;
for(vector<int>::iterator m = nums.begin();m != nums.end();m++)cout << *m << " ";
cout << "i: " << i << endl;
//compare the consequence
if(i == k)return nums[i];
else if(i > k)
{
j = i - 1;
i = ii;
}
else
{
j = jj;
i++;
}
cout << "i:" << i << " j:" << j << endl;
}
}