Week 5: Lists & Insertion Sort

3718 words
19 min read
2026-09-12T00:00:00.000Z
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

Ordered collections, indexing, list manipulation, insertion operations, and the step-by-step Insertion Sort algorithm. # Computational Thinking — Week 5: Lists & Insertion Sort IITM’s CT Week 5 covers **Lists and Insertion Sort**.

Computational Thinking — Week 5: Lists & Insertion Sort

IITM’s CT Week 5 covers Lists and Insertion Sort.

TL;DR

Week 5 introduces an actual data structure and an algorithm that modifies it.
The core ideas are:
  • a list stores multiple ordered values
  • each item has a position/index
  • lists can be read and modified
  • insertion means placing an item at a particular position
  • insertion sort builds a sorted region gradually
  • at every step, one new value is inserted into its correct place
Core mental model:
text
Unsorted list
    ↓
Treat first item as sorted
    ↓
Take next item
    ↓
Shift larger items right
    ↓
Insert item into correct position
    ↓
Repeat

1. What is a list?

A list is an ordered collection of values.
Example:
text
[8, 3, 12, 5]
The important word is:
ordered
There is a first item, second item, third item, and so on.

2. Lists can contain many values

Instead of variables such as:
text
a = 8
b = 3
c = 12
d = 5
we can conceptually store them together:
text
L = [8, 3, 12, 5]
This makes iteration much easier.

3. List position

Every element occupies a particular position.
Conceptually:
PositionValue
18
23
312
45
Some programming languages use zero-based indexing, but when solving IITM pseudocode you should follow the indexing convention used in the question rather than assuming one.

4. Index vs value

Suppose:
text
L = [10, 30, 50]
Then:
  • position/index identifies where
  • value tells you what is stored there
Do not confuse:
text
index = 2
with:
text
value = 30
They are different concepts.

5. Accessing an item

Conceptually:
text
L[i]
means:
value stored at position i.
If:
text
L = [4, 9, 2]
then some indexing convention might give:
text
L[1] = 4
or:
text
L[0] = 4
depending on the notation.
Again: follow the course pseudocode exactly.

6. Updating a list

A list can often be modified.
Example:
text
L = [4, 9, 2]
Suppose second element becomes 7:
text
L = [4, 7, 2]
Conceptually:
text
L[position] = new_value
changes the stored state.

7. List as mutable state

Earlier CT weeks mostly updated variables such as:
text
count
sum
max
Now a whole collection can change.
Example:
text
[8, 3, 5]
might become:
text
[3, 8, 5]
and later:
text
[3, 5, 8]
The list itself records algorithmic progress.

8. Traversing a list

A list naturally supports iteration:
text
for each x in L:
    process x
or index-based iteration:
text
for i through valid positions:
    process L[i]
These are related but not identical.

9. Value iteration vs index iteration

Value iteration

text
for each x in L:
Useful when you only need the current value.

Index iteration

text
for each position i:
Useful when you need to:
  • modify an element
  • compare neighbors
  • insert/shift values
  • access previous positions
Insertion sort needs positional reasoning.

10. Length of a list

The number of elements is the list's length.
For:
text
L = [7, 2, 4, 9]
length:
4\boxed{4}
An empty list has length:
0.0.

11. Empty list

Conceptually:
text
[]
contains no elements.
Some algorithms require a nonempty list.
For example:
text
max = first element
is impossible for an empty list.
So preconditions matter.

12. Insertion into a list

Insertion means adding an element at a chosen position while preserving the order of existing items around it.
Example:
text
[2, 5, 9]
Insert:
text
7
between 5 and 9:
text
[2, 5, 7, 9]

13. Why shifting is needed

Suppose we have:
text
[2, 5, 9, _]
and want to insert:
text
7
before 9.
We must move:
text
9
one position right:
text
[2, 5, _, 9]
then place:
text
7
in the gap:
text
[2, 5, 7, 9]
This shifting idea is central to insertion sort.

14. Sorting

Sorting means arranging elements according to an order.
Ascending:
text
2, 4, 7, 10
Descending:
text
10, 7, 4, 2
Insertion sort usually gets explained using ascending order.

15. Insertion sort intuition

Imagine arranging playing cards in your hand.
You already have some cards sorted.
You pick the next card and slide it into the correct position.
That is essentially insertion sort.

16. Sorted prefix

Insertion sort maintains a sorted prefix.
Example list:
text
[3, 8, 5, 2]
Suppose first two values:
text
[3, 8]
are already sorted.
Next value:
text
5
must be inserted into:
text
[3, 8]
giving:
text
[3, 5, 8]
So list becomes:
text
[3, 5, 8, 2]
Now first three positions are sorted.

17. Core invariant

After each major iteration:
the prefix processed so far is sorted.
That is the key invariant of insertion sort.
Conceptually:
text
[ sorted portion | unprocessed portion ]
As the algorithm progresses:
text
[ S | UUUU ]
[ SS | UUU ]
[ SSS | UU ]
[ SSSS | U ]
[ SSSSS ]

18. Starting condition

A list containing one element is automatically sorted.
So insertion sort begins by treating the first element as a sorted region.
Example:
text
[8 | 3, 5, 2]
Sorted prefix:
text
[8]

19. Insert second element

Current:
text
[8 | 3, 5, 2]
Take:
text
3
Compare with:
text
8.
Since:
3<8,3<8,
shift 8 right:
text
[8, 8, 5, 2]
then insert 3:
text
[3, 8, 5, 2]
Now prefix:
text
[3, 8]
is sorted.

20. Insert third element

Current:
text
[3, 8 | 5, 2]
Take:
text
5.
Compare backward.
With 8:
5<85<8
so shift 8:
text
[3, 8, 8, 2]
Now compare with 3:
5>3.5>3.
Stop shifting and place 5 after 3:
text
[3, 5, 8, 2]

21. Insert fourth element

Current:
text
[3, 5, 8 | 2]
Take:
text
2.
Compare backward:
2<82<8
shift 8.
Then:
2<52<5
shift 5.
Then:
2<32<3
shift 3.
Insert 2 at beginning:
text
[2, 3, 5, 8]
Sorted.

22. Full insertion-sort trace

Start:
text
[8, 3, 5, 2]
Passes:
text
[8, 3, 5, 2]
 ↓
[3, 8, 5, 2]
 ↓
[3, 5, 8, 2]
 ↓
[2, 3, 5, 8]
Final:
[2,3,5,8]\boxed{ [2,3,5,8] }

23. Conceptual pseudocode

A standard insertion-sort structure is:
text
for each position i from second element onward:
    key = L[i]
    j = position immediately before i

    while j is valid AND L[j] > key:
        move L[j] one position right
        move j one position left

    place key in the gap
The exact IITM notation may differ, but the algorithmic idea is this.

24. Why save the key?

Suppose current list:
text
[3, 8, 5]
We want to insert:
text
5.
If we immediately overwrite its position while shifting 8, we might lose 5.
So first:
text
key = 5
stores the value safely.
Then the list positions may be overwritten during shifting.

25. Shift vs swap

Insertion sort is often easier to understand as shifting, not repeated arbitrary swapping.
For:
text
[2, 4, 6, 9, 5]
to insert 5:
shift 9 right:
text
[2, 4, 6, 9, 9]
shift 6 right:
text
[2, 4, 6, 6, 9]
insert 5:
text
[2, 4, 5, 6, 9]

26. Inner backward scan

The algorithm looks backward through the sorted region until it finds where the key belongs.
Condition conceptually:
text
while previous_value > key:
shift previous value right.
Once:
text
previous_value <= key
stop.

27. Example with no shifting

Current sorted prefix:
text
[2, 4, 6]
Next key:
text
9
Since:
9>6,9>6,
it already belongs at the end.
No shifts needed.
Result stays:
text
[2, 4, 6, 9]

28. Example requiring maximum shifting

Current sorted prefix:
text
[3, 5, 7, 9]
Key:
text
1
Every existing value is larger than 1.
So all four shift right.
Result:
text
[1, 3, 5, 7, 9]
This is a worst-case style insertion.

29. Already sorted input

Input:
text
[1, 2, 3, 4, 5]
For every new key, previous value is already smaller.
So very little shifting happens.
Insertion sort performs particularly well conceptually on nearly sorted data.

30. Reverse-sorted input

Input:
text
[5, 4, 3, 2, 1]
Every new key must move all the way toward the front.
This causes many comparisons and shifts.

31. Number of comparisons intuition

In the worst case:
  • second element may compare with 1 previous item
  • third with 2
  • fourth with 3
  • ...
  • last with n−1n-1
Total approximately:
1+2+⋯+(n−1).1+2+\cdots+(n-1).
Using:
1+2+⋯+(n−1)=n(n−1)2,1+2+\cdots+(n-1) = \frac{n(n-1)}2,
the work grows roughly quadratically.

32. Complexity intuition

Insertion sort worst-case work is approximately:
O(n2)\boxed{O(n^2)}
while its best-case behavior on already sorted input can be roughly:
O(n)\boxed{O(n)}
for the usual implementation.
Even if formal asymptotic analysis is not the main Week 5 goal, this is useful intuition.

33. Why nearly sorted input helps

Suppose values are almost in the correct positions.
Then each new key moves only a small distance.
Fewer shifts occur.
So insertion sort can be practical for:
  • small lists
  • nearly sorted data

34. Stable sorting intuition

Insertion sort can be implemented as a stable sort.
Stable means:
equal-valued elements retain their original relative order.
Example:
text
(80, A)
(80, B)
If A originally appears before B, a stable ascending sort keeps A before B.

35. Why comparison operator matters for stability

If shifting condition is:
text
previous > key
equal elements are not shifted past each other.
But if one unnecessarily shifts on:
text
previous >= key
relative ordering of equal elements may change.
This is an important subtlety.

36. Duplicate values

Insertion sort works fine with duplicates.
Example:
text
[4, 2, 4, 1]
sorts to:
text
[1, 2, 4, 4]
The presence of duplicates does not invalidate sorting.

37. Sorting numbers vs records

You can also sort records by a key.
Example:
text
(name, score)
Sort by:
text
score
rather than by the entire record.
This distinction becomes useful later with tables.

38. Example

Data:
text
(A, 70)
(B, 50)
(C, 90)
Sorting by score:
text
(B, 50)
(A, 70)
(C, 90)
The objects move as whole records.

39. List insertion vs insertion sort

Do not confuse:

Insertion into a list

One operation:
put an item at a position.

Insertion sort

Repeatedly performs insertion-like placement to sort the entire list.
The sorting algorithm derives its name from the repeated insertion step.

40. In-place sorting intuition

Insertion sort can usually rearrange elements within the same list without requiring another full list.
This is called in-place sorting in common algorithm terminology.
The list itself evolves:
text
original
→ partially sorted
→ completely sorted

41. Trace table approach

For insertion sort, useful columns are:
PassKeySorted prefix beforeShiftsList after
Example:
Input:
text
[6, 2, 4]
PassKeyPrefixShiftsResult
12[6]6 right[2,6,4]
24[2,6]6 right[2,4,6]

42. Detailed trace example

Input:
text
[7, 4, 5, 2]

Initial

text
[7 | 4, 5, 2]

Insert 4

Shift 7:
text
[7, 7, 5, 2]
Insert 4:
text
[4, 7, 5, 2]

Insert 5

Shift 7:
text
[4, 7, 7, 2]
Insert 5:
text
[4, 5, 7, 2]

Insert 2

Shift:
text
7 → right
5 → right
4 → right
Then:
text
[2, 4, 5, 7]

43. Sorted-prefix invariant

After inserting the element originally at position ii:
first i processed items are sorted\boxed{ \text{first }i\text{ processed items are sorted} }
This is the central correctness argument.

44. Why insertion sort works

Assume prefix is already sorted:
text
[a₁, a₂, ..., aₖ]
Take new key:
text
x
Shift every suffix element larger than xx to the right.
Insert xx after the last value:
≤x.\leq x.
Then the enlarged prefix remains sorted.
Repeat until the whole list is included.

Common mistake: compare against unsorted suffix
Insertion sort's insertion step works within the already sorted prefix.
You do not search arbitrary later elements to decide where the current key belongs.
The algorithm progresses left-to-right.

Common mistake: lose the key
Wrong conceptual behavior:
text
L[i] = L[i-1]
before storing the original L[i].
You may destroy the value that must eventually be inserted.
Save:
text
key = L[i]
first.

Common mistake: shift in wrong direction
To make room for the key, larger elements move:
text
right
not left.
Then the key occupies the newly created gap.

Common mistake: stop too early
Suppose:
text
[2, 8, 10]
and key:
text
5.
Comparing only against 10 is insufficient.
After shifting 10, compare against 8.
Since:
8>5,8>5,
shift 8 too.
Stop only once correct insertion point is found.

Common mistake: move past beginning
When scanning backward, you need both:
  1. index/position is still valid
  2. previous value is greater than key
Conceptually:
text
while j is valid AND L[j] > key:
This prevents accessing a position before the beginning of the list.

50. Why Week 3's AND operator matters here

Notice the insertion-sort loop condition:
text
position valid AND previous value > key
Both must hold.
So Week 3 Boolean logic directly appears in the sorting algorithm.

Common mistake: assume one pass sorts everything
One insertion only guarantees that the current prefix becomes sorted.
Example:
After first insertion:
text
[3, 8, 5, 2]
the entire list is still unsorted.
Only:
text
[3,8]
is guaranteed sorted.

Common mistake: think sorting changes values
Sorting changes positions, not the underlying multiset of elements.
Before:
text
[8,3,5,2]
After:
text
[2,3,5,8]
Same values, same counts.
Only order changes.

53. Permutation invariant

A correct sorting algorithm should preserve all original elements.
So:
output is a permutation of input\boxed{ \text{output is a permutation of input} }
and must additionally satisfy the desired order.
These are the two conceptual requirements for sorting correctness:
  1. no elements lost/created
  2. output ordered

Common mistake: duplicate or lose values while shifting
Suppose:
text
[2, 6, 4]
During shifting, an intermediate state might temporarily look like:
text
[2, 6, 6]
This is okay only because:
text
key = 4
has already been safely stored.
If you forgot the key, you would have lost 4.

55. Ascending vs descending insertion sort

Ascending condition:
text
shift while previous > key
Descending version:
text
shift while previous < key
The algorithmic structure is the same; the comparison direction changes.

56. Finding insertion position

Another conceptual version:
  1. find correct position for key
  2. shift everything after that position
  3. insert key
Whether implemented this way or by backward shifting, the logical goal is identical.

57. List operations mental model

A list lets algorithms perform operations such as:
text
read
update
traverse
insert
rearrange
Week 5's insertion sort combines nearly all of them.

58. Worked example with duplicates

Input:
text
[5, 3, 5, 2]

First insertion

3 into [5]:
text
[3, 5, 5, 2]

Second insertion

key = 5.
Previous value = 5.
For stable ascending insertion sort:
text
5 > 5
is false.
So no shift:
text
[3, 5, 5, 2]

Third insertion

2 moves before all:
text
[2, 3, 5, 5]

59. Worked example: nearly sorted

Input:
text
[1, 2, 4, 3, 5]
First few passes require no shifts.
Only key:
text
3
needs to move before 4.
Result:
text
[1, 2, 3, 4, 5]
Very little movement is needed.

60. Worked example: reverse sorted

Input:
text
[5,4,3,2,1]
Number of shifts:
  • insert 4 → 1 shift
  • insert 3 → 2
  • insert 2 → 3
  • insert 1 → 4
Total:
1+2+3+4=10.1+2+3+4 = \boxed{10}.
For n=5n=5:
5(4)2=10.\frac{5(4)}2=10.

61. Nested-iteration connection

Insertion sort contains an outer progression through the list and an inner backward movement through the sorted prefix.
So it builds naturally on CT Week 4's nested/repeated-work intuition.
In worst case, the total work resembles:
1+2+⋯+(n−1).1+2+\cdots+(n-1).

62. Selection connection

Every shift depends on a condition:
text
previous > key
So sorting uses:
  • lists
  • iteration
  • selection
  • AND
  • state updates
Week 5 combines ideas from the previous weeks rather than replacing them.

63. List trace example

Suppose:
text
L = [9, 4, 7]
and an algorithm does:
text
L[second] = 6
then list becomes:
text
[9, 6, 7]
When a list is modified, all later computations see the new value unless a copy was explicitly stored elsewhere.

64. Aliasing intuition

If two names refer to the same mutable list in some programming model, modifying through one name may affect what is seen through the other.
This depends on the exact semantics used in the course, so do not assume it unless the pseudocode defines it.
The core Week 5 requirement is simply to trace list state carefully.

65. Sorting correctness checklist

At the end of insertion sort, verify:

Ordering

For ascending sort:
L1≤L2≤⋯≤Ln.L_1\leq L_2\leq\cdots\leq L_n.

Preservation

All original values are still present with the same multiplicities.
If either fails, the algorithm/result is wrong.

66. Manual solving strategy

When IITM gives insertion-sort pseudocode:
  1. Write the entire starting list.
  2. Mark the current sorted prefix.
  3. Store the current key separately.
  4. Trace each comparison.
  5. Write every shift.
  6. Insert the key.
  7. Update the sorted-prefix boundary.
  8. Repeat.
Do not mentally jump straight to the final sorted answer if the question asks about intermediate states.

67. Why intermediate states matter

A question may ask:
  • list after second iteration
  • value of j
  • number of comparisons
  • number of shifts
  • sorted portion at some point
Knowing the final sorted list alone cannot answer those.

68. Insertion sort vs "just sort it"

Suppose input:
text
[6, 1, 5, 2]
Final result is obviously:
text
[1,2,5,6]
But CT questions often test:
how the algorithm arrives there.
The procedural trace is the actual skill.

69. Week 5 conceptual map

text
LIST
│
├── ordered elements
├── positions / indices
├── read
├── update
└── insert
       ↓
INSERTION SORT
│
├── sorted prefix
├── choose next key
├── scan backward
├── shift larger items
├── insert key
└── repeat

70. Weeks 1–5 progression

text
Week 1
Variables + iteration
        ↓
Week 2
Selection + max/min
        ↓
Week 3
Multiple passes + procedures
        ↓
Week 4
Nested iteration
        ↓
Week 5
Lists + insertion sort
You have moved from manipulating individual variables to systematically manipulating an entire structured collection.

71. What you should actually master

By the end of CT Week 5, you should be able to:
  1. Explain what a list is.
  2. Distinguish index/position from stored value.
  3. Traverse a list.
  4. Trace list modifications.
  5. Understand insertion into a list.
  6. Explain the sorted-prefix idea.
  7. Trace insertion sort manually.
  8. Identify the current key.
  9. Understand why the key must be stored before shifting.
  10. Shift larger values to the right correctly.
  11. Determine the correct insertion position.
  12. Handle duplicate values.
  13. Understand why one element is trivially sorted.
  14. Explain the insertion-sort invariant.
  15. Recognize best-case nearly/already-sorted behavior.
  16. Recognize worst-case reverse-sorted behavior.
  17. Understand why worst-case work grows roughly like n2n^2.
  18. Verify that sorting preserves all elements while changing their order.
If these are comfortable, Computational Thinking Week 5 is under control.

Quick Recall & Flashcards

Test your active recall before proceeding to practice problems. Format:
Question :: Answer.
  • Week 5 Diagnostic: In 0-indexed list L = [10, 20, 30, 40, 50], what is the value at index 3? :: Answer: 40 — L[0]=10, L[1]=20, L[2]=30, L[3]=40.
  • Week 5 Diagnostic: What is the worst-case time complexity of Insertion Sort on an array of size N? :: Answer: D — When the array is in reverse sorted order, Insertion Sort makes ~N^2 / 2 comparisons and shifts, giving O(N^2) complexity.

Practice & Self-Check

Attempt these diagnostic questions to verify your operational understanding.
1

Question 1

In 0-indexed list L = [10, 20, 30, 40, 50], what is the value at index 3?
NAT
3 Unit Assessment
2

Question 2

What is the worst-case time complexity of Insertion Sort on an array of size N?
MCQ
3 Unit Assessment
A. O(1)
B. O(log N)
C. O(N)
D. O(N^2)

Active Recall Session

Document outline

Keep your place and jump directly to a heading.

Table of contents

No note selected

Open a chapter to see its outline, backlinks, and sources here.