Finding Minimum and Maximum in One Pass
A single traversal can maintain both extremes, which is useful for inputs that can be visited only once.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Start with one observed item
For 6, 2, and 10, both extremes begin at 6. The second item changes the minimum to 2. The last changes the maximum to 10. The running minimum argument extends by applying the opposite comparison to the upper extreme.
Keep the absence outcome
An empty iterator supplies no first value. Return an explicit absent result or raise a documented error, depending on the API. Separate traversals would require a re-readable source. Iterator exhaustion shows why a consumed source cannot supply its second extreme afterward.[1]
Initialize both extremes from a real element
For [-7, -4, -9], begin at (-7,-7), update the largest to \(-4\), then update the smallest to \(-9\). Starting either extreme at zero would allow a result that never occurred in an all-negative or all-positive data set. If the input is empty, define whether to raise an error, return a documented sentinel or carry a separate “has data” flag. Test a singleton and a sequence with the largest value first to exercise the initialization. The sentinel-loop pattern offers a useful comparison when the stream contains an explicit end marker.
Count comparisons if the cost matters
One pass that compares every new value independently to both bounds performs two comparisons after initialization per value. A paired method first orders two new values, then compares the smaller to the current minimum and the larger to the current maximum. That uses three comparisons per pair, with an extra step for an unpaired final item if present. For a small in-memory array, clearer code usually matters more than this constant factor. When returning indices as well as values, use an intentional equality rule. Strict updates retain the first occurrence. See strict and inclusive comparisons for why adding equality changes this result.