【问题标题】:Merge sort worst case running time for lexicographic sorting?合并排序最坏情况下的字典排序运行时间?
【发布时间】:2012-02-14 11:37:47
【问题描述】:

使用归并排序算法将长度为 n 的 n 个字符串按字典顺序排序。这个计算的最坏情况运行时间是?

我把这个问题作为家庭作业。我知道在 O(nlogn) 时间内进行归并排序。对于长度 in 的字典顺序是 n 次 nlogn 吗?还是 n^2 ?

【问题讨论】:

  • 不寻常的问题在于每个字符串的长度与字符串的数量一致。在大多数实际情况下,这将是两个变量,每个最大长度为 m 的 n 个字符串,根据 amit 的回答,结果将是 mnlog(n) 我认为你的老师可能已经做了通过尝试简化问题来解决比必要问题更复杂的问题!

标签: algorithm complexity-theory asymptotic-complexity


【解决方案1】:

算法的每次比较都是O(n) [比较两个字符串是O(n) 最坏的情况-您可能会检测到仅在最后一个字符上哪个“更大”],您在合并排序中有O(nlogn) 比较。

因此你得到O(nlogn * n) = O(n^2 * logn)

【讨论】:

    【解决方案2】:

    但是根据递推关系

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

    将是 T(n) = 2T(n/2) + O(n^2) 当 m = n

    那么结果将是 O(n^2) 而不是 O(n^2logn)。

    如果我错了,请纠正我。

    【讨论】:

    • 通过这种重复,这似乎是正确的。但是@amit 的回答看起来也不错
    【解决方案3】:
    **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)
    

    因此解决了

    【讨论】:

      【解决方案4】:

      时间复杂度递推关系为

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

      很明显,树的高度是 logn。 因此时间复杂度为 O(n^2*logn)。

      【讨论】:

        猜你喜欢
        • 2013-06-03
        • 1970-01-01
        • 2021-08-30
        • 1970-01-01
        • 2011-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-12
        相关资源
        最近更新 更多