› Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 6: Python › MITx 6.100L Introduction to CS and Programming Using Python › Why Do We Insert key at j + 1 in Insertion Sort?
- This topic is empty.
-
AuthorPosts
-
June 17, 2026 at 6:15 am #6905
The Big Idea
When learning Insertion Sort, a common question is:
If
jis initially set toi - 1, then when we placekeyatj + 1, aren’t we just placing it back at positioni?The answer is:
Not necessarily, because
jchanges during the while loop.
The Basic Structure
for i in range(1, len(L)): key = L[i] j = i - 1 while j >= 0 and L[j] > key: L[j + 1] = L[j] j = j - 1 L[j + 1] = keyAt the beginning:
j = i - 1But inside the loop:
j = j - 1moves
jfurther and further to the left.Therefore, by the time we execute:
L[j + 1] = keythe value of
jmay be very different from its original value.
Example 1: Key Must Move Left
Suppose:
L = [5, 2, 4]For:
i = 1we have:
key = 2 j = 0Compare:
L[0] > key 5 > 2True.
Shift:
[5, 5, 4]Decrease
j:j = -1Now the loop stops.
Insert the key:
L[j + 1] = L[0] = 2Result:
[2, 5, 4]Notice:
- Original position of
key= 1 - New position of
key= 0
Therefore:
j + 1 ≠ i
Example 2: Key Already in Correct Position
Suppose:
L = [2, 5, 7]For:
i = 2 key = 7 j = 1Check:
5 > 7False.
The loop never runs.
Therefore:
j = 1still.
Insert:
L[j + 1] = L[2] = 7Here:
j + 1 = ibecause no shifting was required.
What Does
jRepresent?After the while loop finishes:
jpoints to the last element that is less than or equal to
key.So:
j + 1is the exact position where
keyshould be inserted.Think of the array like this:
[ smaller values ] [ empty slot ] [ larger values ] ^ j + 1The larger values have already been shifted one step to the right, creating an empty slot for
key.
Key Insight
During Insertion Sort:
keystays the same.jmoves left.- Elements larger than
keyare shifted right. - The correct insertion position becomes
j + 1.
Therefore, we write:
L[j + 1] = keyinstead of:
L[j] = keybecause
jhas already moved one position too far to the left.
Takeaway
The statement:
j = i - 1is only true at the start of the pass.
As the algorithm runs:
j = j - 1changes the value of
j.Therefore:
L[j + 1] = keyplaces the key in its correct sorted position, which may or may not be the original position
i. - Original position of
-
AuthorPosts
- You must be logged in to reply to this topic.
