quick_sort
//quick_sort
void qSort(int *arr, int start, int end){
if(start >= end) return;
int last = start;
int mid = start + (end - start)/2;
swap(arr[mid], arr[start]);
for(int i = start + 1; i <= end; i++){
if(arr[i] < arr[start])
swap(arr[i], arr[++last]);
}
swap(arr[last], arr[start]);
qSort(arr, start, last - 1);
qSort(arr, last + 1, end);
}
215. Kth Largest Element in an Array
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example, Given [3,2,1,5,6,4] and k = 2, return 5.
Note: You may assume k is always valid, 1 ≤ k ≤ array's length.
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int l = 0 ,r = nums.size() - 1;
while(l <= r){
int index = partition(nums, l, r);
if(index == k - 1)
return nums[k-1];
else if(index < k-1) l = index + 1;
else r = index - 1;
}
return INT_MAX;
}
private:
int partition(vector<int> &nums, int start, int end){
int pivot = nums[start];
int pos = start;
for(int i = start + 1; i <= end; ++i){
if(nums[i] > pivot)
swap(nums[i], nums[++pos]);
}
swap(nums[start], nums[pos]);
return pos;
}
};