We know the time complexity of mergesort is O(n log n). If the lexicographic order is given to merge sort, what will the time complexity be?
-
@RobbyCornelissen: This is not a duplicate of [that](https://stackoverflow.com/questions/9276163/merge-sort-worst-case-running-time-for-lexicographic-sorting). That question states there are n strings of length n. This question does not state the strings are of length n. – Eric Postpischil Oct 03 '19 at 05:27
-
@EricPostpischil Fair enough. Retracted my close vote. – Robby Cornelissen Oct 03 '19 at 05:29
-
2@Raja: The time complexity of a lexicographic comparison depends on the length and content of the strings, but there is no information about these in your question. – Eric Postpischil Oct 03 '19 at 05:30
-
I'm not sure about the question... do you mean that you give a new priority order for each letter? For example, a custom order where `banana` can come before `apple`? If you mean this, the complexity will be the same O(n lg(n)). – Daniel Oct 03 '19 at 05:38
-
Possible duplicate of [Merge sort worst case running time for lexicographic sorting?](https://stackoverflow.com/questions/9276163/merge-sort-worst-case-running-time-for-lexicographic-sorting) – Makyen Oct 05 '19 at 23:53
2 Answers
The complexity won't change.
Suppose your alphabet is abcdefghijklmnopqrstuvwxyz
. In order to compare strings, you can define a hash H
such that H[a] = 0
, H[b] = 1
, ..., H[z] = 25
and compare each character by its value in H
.
That said, you can compare 2 strings in time O(n), where n is the size of the smallest string.
If you change the alphabet to ujklinoyzmvfghwxabpqrstcde
, the comparison time of the 2 strings can remain the same if you change H
to be H[u] = 0
, H[j] = 1
, ..., H[e] = 25
.
Finally, we can state that the complexity time of comparing two strings is the same, given any order of priority of the alphabet, hence this priority order change won't affect the complexity of any sorting algorithm.
The merge sort does O(n lg(n)) comparisons (for n = number of strings), and knowing each comparison O(s) time (for s = size of the string), the total complexity will be O(sn lg(n)).

- 7,357
- 7
- 32
- 84
It will have no effect. This is a trivial (microsecond-level) difference in the amount of work for the computer.

- 8,490
- 5
- 28
- 41
-
3A trivial microsecond-level difference for what number of *n*? – Robby Cornelissen Oct 03 '19 at 03:04