How would you solve if it you were doing it by hand? A basic process might go something like this:
- Keep a set of 3 markers for each of high and low.
- Go over the array(s), and at each new value:
- Determine if the new value fits in the set of lowest or highest
- If it does, replace the one that gets bumped with the new value
Once you've traversed the array(s) once, you'll have your answer. ;)
You may want to consider how to treat duplicate values (i.e. can duplicates be stored more than once in the result lists or should you find unique low/high values).
Infarction
Posting Virtuoso
1,580 posts since May 2006
Reputation Points: 683
Solved Threads: 53
Determining if it's the best depends on how you measure. Since it only reads the array once, my solution is very close to, if not, optimal in terms of performance. Using lots of if-else is not necessarily a bad thing compared to the tradeoff of, say, reading the whole array for each value you need in the result.
Though it might be a little more difficult, you could try keeping the small and large sublists (of 3 values) sorted, so you only have to compare to the largest one in the small list and to the smallest one in the large list. It would reduce the number of if-else's you had, but would require more overhead to track which one to compare to.
Infarction
Posting Virtuoso
1,580 posts since May 2006
Reputation Points: 683
Solved Threads: 53
Infarction is correct. Probably the easiest way to start this solution is one value at a time. Find the min and max. When you understand that, add the second min and max. Etc.
WaltP
Posting Sage w/ dash of thyme
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944