Notes: I\'ve thought about Radix sort, bucket sort, counting sort.
Is there anyway to achieve big O(n)?
For anyone interested, I quickly threw together this piece of Ruby, before reading the answers:
module Enumerable
def counting_sort(k)
reduce(Array.new(k+1, 0)) {|counting, n| counting.tap { counting[n] += 1 }}.
map.with_index {|count, n| [n] * count }.flatten
end
end
ary = Array.new(1_000_000){ rand(100) + 1 }
ary.counting_sort(100) # I'll spare you the output :-)
I didn't even know it had a name. It should convey the idea even to someone who has never seen Ruby before. (The only thing you need to know is that the K combinator is spelled tap
in Ruby.)
And it really is pretty darn fast, although unfortunately I have not been able to beat the builtin hand-optimized O(n log n) sort, which is written in C in MRI and YARV and Java in JRuby.
how about just counting the occurrence of each integer and then printing them all. sounds like O(n)