Nested loops into mathematical model to count number of operations

后端 未结 4 473
野性不改
野性不改 2021-01-13 12:24

I\'m reading the book \'Algorithms - Fourth edition\' by Sedgewick and Wayne and I must admit that some parts in the \"Analysis of Algorithms\" chapter are confusing me! Thi

相关标签:
4条回答
  • 2021-01-13 12:40

    You can use Sigma notation and discover how to come up with the formula mentioned in your book:

    enter image description here

    0 讨论(0)
  • 2021-01-13 12:46

    The 6 is derived from 3! (three factorial derived from three loops).

    Consider the outer-most loop on, say, an array of 5 elements. You're counting N=5 for that part of the equation, but you'll only reach your inner loop for values i=0, i=1 or i=2. Similarly, you're representing the next loop by (N-1), but you'll only reach your inner loop for values j=1, j=2, or j=3 and not the four values implied by (N-1).

    Dividing by 6 (for three loops) compensates for the values that would run out of values in the array before reaching the inner-most loop.

    0 讨论(0)
  • 2021-01-13 12:54

    As we know...

    1+2+3+4...+N => N(N-1)/2

    Similarly, the innermost loop works something like

    1.n+2(N-1)+3(N-2)+...N.1 => N(N-1)(N-2)/6

    Here is a proof for this.

    0 讨论(0)
  • 2021-01-13 12:59

    If you can understand the N(N-1)(N-2) part, here's a thought:

    Take a combination of 3 numbers, i, j, k, whatever 3 that fall into the range 0 <= i,j,k < N and different one from another (this is also taken care in the code and that's why the formula is N(N-1)(N-2) and not N^3.

    Now, lets say the numbers are 13, 17, 42. It doesn't really matters whoch numbers they are. In how many ways can you put them in line?

    13-17-42
    13-42-17
    17-13-42
    17-42-13
    42-13-17
    42-17-13
    

    Six!

    How many of these ways can appear in the code? Only one! (that's taken care in the initializaton of j and k).

    So, the total number of N(N-1)(N-2) should be divided by 6.

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