public class FindKthLargest {
public static int findKthLargest(int[] nums, int k) {
return quickSelect(nums, 0, nums.length - 1, k);
}
public static int quickSelect(int[] nums, int low, int high, int k) {
if (low == high) {
return nums[low];
}
int pivotIndex = partition(nums, low, high);
int rightSize = high - pivotIndex + 1;
if (rightSize == k) {
return nums[pivotIndex];
} else if (rightSize > k) {
return quickSelect(nums, pivotIndex + 1, high, k);
} else {
return quickSelect(nums, low, pivotIndex - 1, k - rightSize);
}
}
public static int partition(int[] nums, int low, int high) {
int pivot = nums[low];
int i = low + 1;
int j = high;
while (true) {
while (i <= j && nums[i] > pivot) {
i++;
}
while (i <= j && nums[j] < pivot) {
j--;
}
if (i <= j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
} else {
break;
}
}
int temp = nums[low];
nums[low] = nums[j];
nums[j] = temp;
return j;
}
public static void main(String[] args) {
int[] nums = {3, 2, 1, 5, 6, 4};
int k = 2;
int result = findKthLargest(nums, k);
System.out.println("The " + k + "th largest element is: " + result);
}
}