Solution: Sorting the Array
The most direct solution is to sort the array and read off the answer. Once the values are in ascending order, the largest is at the last index, the second largest one before it, and the kth largest is k positions from the end, at index numbers.length - k.
public static int findKthLargestSorting(int[] numbers, int k) {
Arrays.sort(numbers); // ascending
return numbers[numbers.length - k];
}
On numbers = [3, 1, 5, 2, 4] with k = 2, sorting gives [1, 2, 3, 4, 5], and index 5 - 2 = 3 holds 4, the second largest:
┌───┬───┬───┬───┬───┐
│ 1 │ 2 │ 3 │ 4 │ 5 │
└───┴───┴───┴───┴───┘
↑ ↑
2nd 1st
Sorting dominates the cost. With an efficient sort, such as merge sort, the whole solution is . The method also changes the caller’s array, because it sorts numbers in place.