Recipe 4.11. Getting the N Smallest Items of an ArrayProblemYou want to find the SolutionIf you only need to find the single smallest item according to some measure, use
Similarly, if you need to find the single
By default, arrays are sorted by their natural order: numbers are sorted by value, strings by their position in the ASCII collating sequence (basically alphabetical order, but all lowercase characters precede all uppercase characters). Hence, in the previous examples, "three" is the largest string, and "eleven" the smallest. It gets more complicated when you need to get a number of the smallest or largest elements according to some measurement: say, the top 5 or the bottom 10. The simplest solution is to sort the list and skim the items you want off of the top or bottom.
Despite the simplicity of this technique, it's inefficient to sort the entire list unless the number of items you want to extract approaches the size of the list. DiscussionThe min and max methods work by picking the first element of the array as a "champion," then iterating over the rest of the list trying to find an element that can beat the current champion on the appropriate metric. When it finds one, that element becomes the new champion. An element that can beat the old champion can also beat any of the other contenders seen up to that point, so one run through the list suffices to find the maximum or minimum. The naive solution to finding more than one Sorting the list beforehand is better when you need to find more than a small fraction of the items in the list, but it's possible to do better. After all, you don't really want to sort the whole list: you just want to sort the bottom of the list to find the smallest items. You don't care if the other elements are unsorted because you're not interested in those elements anyway. To sort only the smallest elements, you can keep a sorted "stable" of champions, and kick the The SortedList class from Recipe 4.7 is useful for this task. The min_n method below creates a SortedList "stable" that keeps its elements sorted based on the same block being used to find the minimum. It keeps the stable at a certain size by kicking out the
See Also
|
Saturday, October 24, 2009
Recipe 4.11. Getting the N Smallest Items of an Array
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment