Finding the n largest values in an array is a complex variant of Finding the minimum or maximum.

findNLargest method

/*
 * Returns an array containing the n largest values in nums,
 * sorted in ascending order.
 * Leaves the values in nums unchanged.
 * Precondition: nums.length >= n
 */
public static int[] findNLargest(int[] nums, int n)

The Java files below include skeleton code for the method and a JUnit 5 tester. See Running JUnit 5 tests.

NLargest.java
TestNLargest.java

Examples of calls to findNLargest(nums, n)

nums n Returned array
[71, 86, 79, 36, 78, 35, 75, 86, 24, 11] 5 [75, 78, 79, 86, 86]
[37, 32, 70, 15, 93, 40, 63, 3, 40, 63] 3 [63, 70, 93]
[71, 86, 79, 36, 78, 35, 75, 86, 24, 11] 10 [11, 24, 35, 36, 71, 75, 78, 79, 86, 86]
[37, 32, 70, 15, 93, 40, 63, 3, 40, 63] 10 [3, 15, 32, 37, 40, 40, 63, 63, 70, 93]
[71, 86, 79, 36, 78, 35, 75, 86, 24, 11] 0 []
[] 0 []

Solution & comments

See the Find the n largest values solution or review it with AP CS Tutor Brandon Horn

Comment on Finding the n largest values in an array