Get Two Maximum values from array of numbers

Hi, I’ve got an array of numbers that looks like this:

int [] numbers = { 2, 3, 8, 1, 8, 9, 6 };

I need to write a function that identifies 8 & 9 as the highest integers.
I’ve seen plenty of solutions for returning one value but not two, would greatly appreciate any help!

This is in case you want to increase the found elements later on from just the 2 highest to more

First you‘d want to remove all the duplicates.

For that, you need to go through each Element of the array and check wether it‘s already been there.

Which you can do with 2 ways, one by adding them to another array and then just compare, or by simply comparing them to all the other Elements in the array and check if you found another one.

If so, remove the duplicates.

Now, create a second int array of size 2. (we‘ll call it result

Set result[0] to the first Element of the other array and result[1] to the second.

Then just loop over the first array, starting from the index 2.

Within the loop, check if the number is bigger than any of the 2 values in result.

If it is, replace each element in result with the one before it ([1]=[0])and then set the first to our new highest value and then break the loop (using break;).

Once this is done, you‘ll have an array result of size 2 with [0] being 9 and [1] being 8.

Else, if you only want the 2 highest

Just create 2 variables (4 if you want the actual int reference, not just the value)

Loop through the whole array.

If the value is higher than var1, set var2 to var1 and var1 to the value. (And set idx2 to idx1 and idx1 to the current index, if you want this too).

Done. Var1 is the highest, while var2 is the second highest

1 Like

Depending on the problem domain, this may be a good time to use sorting algorithms, or Processing / Java’s built-in sort for arrays or integer lists (IntList).

Once a list is sorted, by its nature you can take items from the beginning or end of the list, and the first or last 2 items, 3 items, 4 items, or n items and that will give you the n highest / lowest items. So, if you had a list of 10 items and wanted to know the top 8, you could get them. A nice byproduct of this approach is that you also get them already-sorted.