What is the fastest way to sort 1 million integers when integers are from the range [1,100]?

前端 未结 8 1618
慢半拍i
慢半拍i 2020-12-23 22:13

Notes: I\'ve thought about Radix sort, bucket sort, counting sort.

Is there anyway to achieve big O(n)?

相关标签:
8条回答
  • 2020-12-23 22:31

    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.

    0 讨论(0)
  • 2020-12-23 22:35

    how about just counting the occurrence of each integer and then printing them all. sounds like O(n)

    0 讨论(0)
提交回复
热议问题