This is about the analysis of insertion sort in the book ‘Introduction to Algorithms’. It says that following for loop executes n(=A.length) times:
for j = 2 to A.length
....
Can anyone tell me why this loop executes n times rather than n-1 times?
Thanks,
Ganesh
I found the answer my self:
For the loop for j = 2 to 5
1st iteration: j is set to 2 and the loop condition evaluates to true.
2nd iteration: j is incremented to 3 and the loop condition evaluates to true.
3rd iteration: j is incremented to 4 and the loop condition evaluates to true.
4th iteration: j is incremented to 5 and the loop condition evaluates to true.
5th iteration: j is incremented to 6 and the loop condition evaluates to false and the loop is exited.
So the for statement is executed 5 times although the statements inside the loop are executed 4 times.