Nested loops into mathematical model to count number of operations

后端 未结 4 479
野性不改
野性不改 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: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.

提交回复
热议问题