Sorting n items with MergeSort requires O(N LogN)
. If the time for comparing the two elements is O(1)
, then the total runtime will be O(N LogN)
. However, comparing two strings of length N requires O(N)
, so a naive implementation may depend on O(N*N logN)
.
This seems wasteful because we are not using the fact that there are only N
strings for comparison. We could somehow manipulate the strings so that comparisons on average take less time.
Here is an idea. Create a Trie structure and place N lines there. The trie will have O(N*N)
nodes and it takes O(N*N)
to build. Go through the tree and put the whole "ranking" in each node in the tree; If R (N1) <R (N2), then the line associated with Node1 precedes the line associated with Node2 in the dictionary.
Now continue with Mergesort, compare in O(1)
time by looking at Trie. Total run time will be O(N*N + N*logN)
= O(N*N)
Edit: My answer is very similar to @amit. However, I am starting to merge, where he continues to work with radixsort after the trie build phase.
source share