Fast sort algorithms for arrays with mostly duplicated elements?

后端 未结 5 844
野的像风
野的像风 2021-01-11 17:03

What are efficient ways to sort arrays that have mostly a small set of duplicated elements? That is, a list like:

{ 10, 10, 55, 10, 999, 8851243, 10, 55, 55, 55, 10

5条回答
  •  太阳男子
    2021-01-11 17:20

    In practice, you can first iterate through the array once and use a hash table the count the number of occurrences of the individual elements (this is O(n) where n = size of the list). Then take all the unique elements and sort them (this is O(k log k) where k = number of unique elements), and then expand this back to a list of n elements in O(n) steps, recovering the counts from the hash table. If k << n you save time.

提交回复
热议问题