2

A list of n strings each of length n is sorted into lexicographic order using the merge sort algorithm. The worst case running time of this computation is?

I got this question as a homework. I know merge sort sorts in O(nlogn) time. For lexicographic order for length in is it n times nlogn ? or n^2 ?

user567879
  • 5,139
  • 20
  • 71
  • 105
  • Unusual question in that the length of each string is coincidental with the number of strings. In most practical cases this will be two variables, n strings each of max length m, and the result as per amit's answer, would then be m*n*log(n) I think your teacher may have made the question more complicated than necessary by trying to simplify it! – SmacL Feb 14 '12 at 12:59

4 Answers4

7

Each comparison of the algorithm is O(n) [comparing two strings is O(n) worst case - you might detect which is "bigger" only on the last character], You have O(nlogn) comparisons in mergesort.

Thus you get O(nlogn * n) = O(n^2 * logn)

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
amit
  • 175,853
  • 27
  • 231
  • 333
0

Time complexity recurrence relation is

T(a,b)=2T(a/2,b)+O(b^2)

So clearly the height of tree would be logn. Thus time complexity is O(n^2*logn).

0

But according to the recurrence relation

T(n) = 2T(n/2) + O(m*n)

Will be T(n) = 2T(n/2) + O(n^2) when m = n

Then the result will be O(n^2) and not O(n^2logn).

Correct me if I'm wrong.

Manjeet Dahiya
  • 485
  • 1
  • 4
  • 15
0
**answer is O(n^2logn)
  , 
we know Merge sort has recurrence form
T(n) = a T(n/b) + O(n)
in case of merge sort 
it is 
T(n) = 2T(n/2) + O(n) when there are n elements
but here the size of the total is not "n" but "n string of length n"
so a/c to this in every recursion we are breaking the n*n elements in to half
for each recursion as specified by the merge sort algorithm
MERGE-SORT(A,P,R)  ///here A is the array P=1st index=1, R=last index in our case it 
                      is n^2 
if P<R
then Q = lower_ceiling_fun[(P+R)/2]
      MERGE-SORT(A,P,Q)
      MERGE-SORT(A,Q+1,R)
      MERGE (A,P,Q,R)
MERGE(A,P,Q,R) PROCEDURE ON AN N ELEMENT SUBARRAY TAKES TIME O(N)
BUT IN OUR CASE IT IS N*N
SO A/C to this merge sort recurrence equation for this problem becomes
T(N^2)= 2T[(N^2)/2] + O(N^2)
WE CAN PUT K=N^2 ie.. substitute to solve the recurrence
T(K)= 2T(K/2) + O(K)
a/c to master method condition T(N)=A T(N/B) + O(N^d)
                               IF A<=B^d  then T(N)= O(NlogN)
therefore T(K) = O(KlogK)
substituting K=N^2
we get T(N^2)= O(n*nlogn*n)
       ie.. O(2n*nlogn)
         .. O(n*nlogn)

hence solved

sumit r
  • 1
  • 1