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
You can use Sigma notation and discover how to come up with the formula mentioned in your book:
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.
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.
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
.