Trying to compare a recursive and an iterative algorithm

后端 未结 2 1057
陌清茗
陌清茗 2021-01-26 23:35

I have two algorithms that solve this problem: Generate all sequences of bits within Hamming distance t. Now I want to compare them theoretically (I do have time measurements, i

相关标签:
2条回答
  • 2021-01-27 00:10

    At the most general level of time complexity, we have a "worst case" of t = n/2. Now, fix t and gradually increment n. Let's take a starting point of n=8, t=4

    C(8 4) = 8*7*6*5*4*3*2*1 / (4*3*2*1 * 4*3*2*1)
        = 8*7*6*5 / 24
    n <= n+1 ... n choose t is now
    
    C(9 4) = ...
        = 9*8*7*6 / 24
        = 9/5 of the previous value.
    

    Now, the progression is a little easier to watch.

    C( 8 4) = 8*7*6*5 / 24
    C( 9 4) =  9/5 * C( 8 4)
    C(10 4) = 10/6 * C( 9 4)
    C(11 4) = 11/7 * C(10 4)
    ...
    C( n 4) = n/(n-4) * C(n-1 4)
    

    Now, as lemmas for the student:

    • Find the base complexity, n! / ( (n-1)! ^ 2)
    • Find the combinatorial complexity of product (n / (n-c)) for constant c
    0 讨论(0)
  • 2021-01-27 00:11

    The recursive algorithm is O((n choose t) * n) too, by an analysis that charges to each printed combination the cost of the entire call stack at the time that it is printed. We can do this because every invocation of magic (except the two O(1) leaf calls where i < 0, which we could easily do away with) prints something.

    This bound is best possible if you assign printing its true cost. Otherwise, I'm pretty sure that both analyses can be tightened to O(n choose t) excluding printing for t > 0, with details in Knuth 4A.

    0 讨论(0)
提交回复
热议问题