Fast sort algorithms for arrays with mostly duplicated elements?

后端 未结 5 833
野的像风
野的像风 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:25

    I would try Counting sort with some mapping function. Ie. you wont use the frequencies array of size equal to the range of elements, instead you would iterate over the array, write down distinct elements and use them in a mapping function to the array of frequencies.

    This way the algorithm has only one extra iteration and a mapping function, which should work in a constant time (using some kind of hash table). The complexity of this approach would be O(n), which should be optimal.

提交回复
热议问题