On Thursday, November 8, 2012 5:13:08 PM UTC+2, Nicolas Oury wrote:
There are algorithms that can do that in expected O(n), like QuickSelect. The lazy quicksort above, though nice and clever, sorts a bit too much to be as good as that, I think.
Yeah, I know, thanks for the tip, but I was wondering about what can one do with lazy collections in algorithms.
Like, if you think about it, most QuickSort implementations developed without attention to picking the pivot are O(n ^ 2) for common use-cases (e.g. sorting an already sorted collection or one that's almost sorted), as that's what happens when you pick the head as the pivot. This can also happen with QuickSelect if you're not careful, the worst case being O(n ^ 2), like when you pick the head and the collection is in descending order with a small K, or when the collection is in ascending order and K is close to N.
With a lazy sorted() on a lazy list, you'd get simplicity of implementation, O(k) extra storage used and a guaranteed O(kn). And if K is a constant close to the edges (0 or N-1), then you can consider it O(n), because in case it's close to N-1, then you can just sort in descending order and pick (N-K+1).