Fast sort algorithms for arrays with mostly duplicated elements?

后端 未结 5 910
野的像风
野的像风 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-11 17:30

    Not the best algorithm, but simple:
    You can put everything in a trie, and have the leaves be counters. That should take O(n*m) where n is the number of elements and m is the size of the biggest element (typically that would be a constant, but not necessarily). Then pre-order traverse the tie, outputting counter elements of the current key when you hit a leaf. That should take only O(n+p) where p is the size of the trie, which should be tiny compared to n.

提交回复
热议问题