Hey guys. I'm supplementing my DSA course at Uni with CLRS, and I'm a little confused about the following paragraph discussing the reasoning behind Insertion-Sort having an upper bound of O(n2):
"The running time is dominated by the inner loop. Because each of the (n - 1) iterations of the outer loop causes the inner loop to iterate at most (i - 1) times, and because i is at most n, the total number of iterations of the inner loop is at most (n - 1)(n - 1)." (this is page 52 of the 4th edition)
Here is the pseudocode:
Insertion-Sort(A, n)
for i = 2 to n
key = A[i]
j = i - 1
while j > 0 and A[j] > key
A[j + 1] = A[j]
j--
A[j + 1] = keyIt is true that the outer loop of the insertion sort pseudocode in CLRS runs (n - 1) times regardless of the problem instance, and that at most, the inner while loop executes (i - 1) times for each iteration.
However, I'm confused about why the author states that the inner while loop runs at most (n-1)(n-1) times. The inner while loop only has the opportunity to execute (n - 1) times when i assumes the value of n, which of course only occurs once during the last iteration, not every (n - 1) iterations.
Wouldn't the number of iterations of the inner while loop be determined by the summation 1 + 2 + 3 + ... + (n - 1) = n(n - 1) / 2 ?
In either case, the O(n2) upper bound is correct, but I need some clarity on the author's reasoning, as I don't seem to be following it.