Finding Maximum and Minimum

Part of: Array

A Standard Algorithm Finding the maximum or minimum value in an array is one of the standard algorithms the AP CS A exam expects you to write fluently. The idea: assume the first element is the best so far, then compare it against every other element. The Max Pattern Key points: - Initialize max to a[0] , not to 0. If you start at 0 and all values are negative, you would wrongly return 0. - Start the loop at index 1 since index 0 is already the initial guess. - The condition a[i] max updates the running best whenever a larger value appears. The Min Pattern Finding the minimum is identical except the comparison flips to <: Notice this version uses an enhanced for loop , which works fine because we are only reading. Comparing a[0] against itself on the first iteration is harmless. Tracking the Index of the Max Sometimes you need where the max is, not just its value. Track an index instead: Then a[maxIndex] is the maximum and maxIndex tells you its position. This index-tracking variation appears often in free-response questions, so practice both forms.

Challenge: Largest Element