2

I am currently reading chapter 2 of the TCRC Introduction to Algorithms 3rd edition textbook and I am reading the author's interpretation of the loop invariant of this algorithm. I understand the author's logic for both the initialization and the maintenance. However, the termination is what I am kind of bogged up on. The author claims that at termination, j = n + 1. However, in the pseudocode of the algorithm, j loops from 2 to n. So shouldn't j = n - 1?

EDIT: The book's pseudo-code for insertion sort is:

for j = 2 to A.length
    key = A[j]
    // Insert A[j] into sorted sequence A[1...j - 1]
    i = j - 1
    while i > 0 and A[i] > key
        A[i + 1] = A[i]
        i = i  - 1
    A[i + 1] = key

EDIT: After reading it carefully, I have finally understood why j = n + 1 during termination. It's because the for loop goes from 2 to n (inclusively), so after j exceeds n, the loop terminates, hence why j = n + 1 at termination. I appreciate the help.

1 Answers1

1

Disclaimer: this can be totally incorrect... It is just a brain spit.

Side note: since j is incremented during this loop, the starting point is irrelevant for the end condition.

 for j = 2 to A.length //A.length = n in your question

There is a bit of ambiguity in this pseudo code.

First of all, we assume j is defined outside this for loop and will have an end value when the loop is terminated. see @Dukeling's comment

Second, your code is targeting an array, using the j as indexer: A[j]

The ambiguity exist with the word to in for j = 2 to A.length, is it including or excluding A.length? and there is this indexer A[j]

In common cases, for the indexer in A[j], the valid range for j is [0...A.length -1]

Some languages uses another range, namely: [1...A.length] I think this is intended by the author because A[0] is not being hit at all.

If that's the case.... and the for condition increments j before it breaks the loop (to test the condition and see that it is false), then... you'll get j = A.length + 1.

As a side note:

In common C like languages, arrays have a valid range from [0...A.length -1].

And in this C example, c has the value of A.length after termination:

int c = 0;
for (c = 3; c < A.length; c++)
{

}
//c = A.length after the loop is completed.
Stefan
  • 17,448
  • 11
  • 60
  • 79
  • 1
    We don't really have to assume `j` is defined outside the loop - `j` does increment the final time regardless of where it's defined. – Bernhard Barker Nov 07 '17 at 23:23
  • @Dukeling: You are right on the first part, but as for the second, the focus on 0-indexed, I think that's what caused OP's confusion. Not sure though. – Stefan Nov 07 '17 at 23:27
  • After reading the pseudocode convention the author uses (same section as the pseudocode in OP), I believe that the author is specifying the index j is at position n + 1, which kind of makes sense considering that the loop ends after the index exceeds the last element of the array. – JoeyCentral Nov 08 '17 at 00:46