I am going through exercies for an exam in algorithm analysis and this is one of them:
Present an algorithm that takes as input a list of n elements (that
are comparable) and sorts them in O(n log m) time, where m is the
number of distinct values in the input list.
I have read about the common sorting algorithms and I really can’t come up with a solution.
Thanks for your help
You can build an augmented balanced binary search tree on the
nelements. The augmented info stored at each node would be it’s frequency. You build this structure withninsertions into the tree, the time to do this would beO(n lg m), since there would be onlymnodes. Then you do a in-order traversal of this tree: visit the left subtree, then print the element stored at the rootftimes wherefis it’s frequency (this was the augmented info) and finally visit the right subtree. This traversal would take timeO(n + m). So, the running time of this simple procedure would beO(n lg m + n + m) = O(n lg m)sincem <= n.