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

前端 未结 8 1617
慢半拍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:17

    A counting sort would be the obvious choice under these circumstances. Yes, properly implemented it should have linear complexity.

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

    With counting sort you get O(N) if the range is fixed and small (like 1..100 :))

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

    Here is a counting sort in scala:

    val res = Array.fill (100)(0)
    val r = util.Random 
    // generate data to sort
    val nums = for (i <- 1 to 1000*1000) yield r.nextInt (100)
    for (i <- nums) res(i) += 1
    println (res.mkString (" ")) 
    
    0 讨论(0)
  • 2020-12-23 22:26

    I assume, you mean you want to achieve a small O(n); then bucket sort would be fastest. In fact, since you know the range of the integers, then using bucket sort simply becomes a problem of counting the occurrences of the numbers which can be done in O(n), i.e. linear time.

    The so-called counting sort is simply a special case of bucket sort.

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

    You can use counting sort.

    Counting sort (sometimes referred to as ultra sort or math sort) is a sorting algorithm which (like bucket sort) takes advantage of knowing the range of the numbers in the array to be sorted (array A).

    Counting sort is a stable sort and has a running time of Θ(n+k), where n and k are the lengths of the arrays A (the input array) and C (the counting array), respectively. In order for this algorithm to be efficient, k must not be much larger than n.

    In this case k is 100 and n is 1000000.

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

    Using Radix Sort (In Ruby):

    def sort(array)
    sorted_array = Array.new(100,[])
    array.each do |t|
    sorted_array[t-1] = sorted_array[t-1] + [t]
    end
    sorted_array.flatten!
    end
    
    0 讨论(0)
提交回复
热议问题