› 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 › Understanding Why Insertion Sort Uses L[j + 1] = key
- This topic is empty.
-
AuthorPosts
-
June 20, 2026 at 6:50 am #6956
Insertion Sort is one of those algorithms that seems simple at first, but a small detail can be confusing:
Why do we insert the key at
j + 1instead ofj?Let’s break it down with an example.
Example List
L = [3, 5, 7, 4]When processing the element
4:key = 4 j = 2Current situation:
Index: 0 1 2 3 Value: 3 5 7 4 j keyStep 1: Compare with 7
Since:
4 < 7shift 7 one position to the right:
L[3] = L[2]Result:
Index: 0 1 2 3 Value: 3 5 7 7Move left:
j = 1Step 2: Compare with 5
Since:
4 < 5shift 5 one position to the right:
L[2] = L[1]Result:
Index: 0 1 2 3 Value: 3 5 5 7Move left:
j = 0Step 3: Compare with 3
Now:
4 < 3is False.
The loop stops.
Current state:
Index: 0 1 2 3 Value: 3 5 5 7 jNotice something important:
jpoints to the value3.3should stay to the left of4.- Therefore,
4should be inserted immediately after index0.
That position is:
j + 1So:
L[j + 1] = keybecomes:
L[1] = 4Result:
Index: 0 1 2 3 Value: 3 4 5 7What If
jBecomes -1?Consider:
L = [2, 1]Initial values:
key = 1 j = 0Since:
1 < 2we shift:
L[1] = L[0]Result:
[2, 2]and:
j = -1The loop stops.
Now
j = -1means:We reached the beginning of the list without finding any element smaller than or equal to the key.
Therefore the insertion position is:
j + 1 = -1 + 1 = 0So:
L[0] = 1Result:
[1, 2]Key Insight
When the while loop ends:
jpoints to the last element that should remain to the left ofkey.- Therefore the correct insertion position is always one place to the right of
j.
Visual representation:
[ elements <= key ] j [ elements > key ] ^ insert key hereThat is why the final statement in Insertion Sort is:
L[j + 1] = keyand not:
L[j] = keyor
L[j - 1] = keyCorrect Insertion Sort Code
def insertionsort(L): for i in range(1, len(L)): key = L[i] j = i - 1 while j >= 0 and key < L[j]: L[j + 1] = L[j] j = j - 1 L[j + 1] = key return LUnderstanding why
j + 1is used is one of the most important concepts in mastering the Insertion Sort algorithm. -
AuthorPosts
- You must be logged in to reply to this topic.
