Trying to Count the Number of Operations in Code

galmquist :

I have recently been reading Sedgewick's Algorithms Book, and I came across an example I didn't quite understand...

The code in question

Using this code, Sedgewick mentions that the if statement is run precisely N x (N-1)(N-2)/6 times.

I don't quite understand why that is.... I see that there are the triple nested loops, each with an upper bound that is increasing, but why is the value divided by six?

J4BEZ :

I ask for your understanding that I am not good at math, so the explanation may be a little bit cheesy.

In order to 'if(a[i] + j[i] + k[i]) statement' inside the code be executed The variables i, j, and k that point out an array 'a' index in Tripple for loop must fit the condition of the statement (0<= i <j<k <N), right?

For example, N is 4. enter image description here It seems to be available through the permutation (4P3 = 4^3) that selects three of the four, but if 4 is selected in 'i' as shown in the picture above, you can see that progress is blocked in 'j' for-loop (j = 4+1; j<4; j++).

So We can't get the number of times an if statement will run with a simple sequence.

What we need is a combination (nCr).

When index flows from 0 to N-1, The number of cases (i,j,k) that satisfy i < j < k(=> if statement can run) can be obtained by the formula nC3.

enter image description here According to this formula, if statement is run precisely N x (N-1)(N-2)/6 times

I hope you understand it well and if you don't, please leave a comment! Have a nice day!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=238084&siteId=1