Implement a C++ function that finds the Kth largest element in an unsorted array using the Quickselect algorithm. Ensure that the solution runs in average O(n) time complexity.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Finding the Kth Largest Element Using QuickSelect Algorithm
The QuickSelect algorithm is an efficient selection algorithm to find the Kth smallest (or largest) element in an unsorted array. It works by utilizing the partitioning technique from QuickSort but only recurses on one side of the partition, making it faster than full sorting algorithms when we only need to find a single element.
Below is a complete C++ implementation that finds the Kth largest element in an unsorted array using the QuickSelect algorithm:
cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib> // for rand()
// Partitions the array and returns the index of the pivot
int partition(std::vector<int>& nums, int left, int right) {
int pivot = nums[right]; // Choose the rightmost element as pivot
int i = left;
for (int j = left; j < right; j++) {
if (nums[j] <= pivot) {
std::swap(nums[i], nums[j]);
i++;
}
}
std::swap(nums[i], nums[right]);
return i;
}
// Randomized partition to improve average-case performance
int randomPartition(std::vector<int>& nums, int left, int right) {
int randomIndex = left + rand() % (right - left + 1);
std::swap(nums[randomIndex], nums[right]);
return partition(nums, left, right);
}
// QuickSelect algorithm to find the kth smallest element
int quickSelect(std::vector<int>& nums, int left, int right, int k) {
if (left == right) {
return nums[left];
}
int pivotIndex = randomPartition(nums, left, right);
if (k == pivotIndex) {
return nums[k];
} else if (k < pivotIndex) {
return quickSelect(nums, left, pivotIndex - 1, k);
} else {
return quickSelect(nums, pivotIndex + 1, right, k);
}
}
// Function to find the kth largest element
int findKthLargest(std::vector<int>& nums, int k) {
// To find kth largest, we need to find (n-k)th smallest
int n = nums.size();
return quickSelect(nums, 0, n - 1, n - k);
}
// Example usage
int main() {
std::vector<int> nums = {3, 2, 1, 5, 6, 4};
int k = 2; // Find the 2nd largest element
std::cout << "The " << k << "th largest element is: "
<< findKthLargest(nums, k) << std::endl;
return 0;
}
Understanding the Implementation
This implementation follows these key steps:
Partition Function: Rearranges elements around a pivot so that elements less than the pivot are on the left and greater elements are on the right[3][4].
Random Pivot Selection: Uses a randomized approach for selecting pivots to improve average-case performance and avoid the O(n²) worst-case scenario with already sorted arrays[6].
QuickSelect Algorithm: Recursively partitions the array and only processes the relevant portion that contains the target element[3][10].
Kth Largest Conversion: To find the kth largest element, we convert it to finding the (n-k)th smallest element, where n is the array size[9][10].
Time and Space Complexity
Average Time Complexity: O(n), as the algorithm typically only needs to process one partition in each recursive step[3][10].
Worst-case Time Complexity: O(n²), which occurs when poor pivot choices consistently result in highly imbalanced partitions[3].
Space Complexity: O(1) for auxiliary space as the algorithm works in-place, plus O(log n) average-case space for the recursion stack[4].
The randomized pivot selection significantly improves the probability of achieving the O(n) average-case performance, making this a practical and efficient solution for finding the Kth largest element in an unsorted array.