Week 5: Lists & Insertion Sort
3718 words
19 min read
2026-09-12T00:00:00.000Z
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:
textUnsorted 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:
texta = 8 b = 3 c = 12 d = 5
we can conceptually store them together:
textL = [8, 3, 12, 5]
This makes iteration much easier.
3. List position
Every element occupies a particular position.
Conceptually:
| Position | Value |
|---|---|
| 1 | 8 |
| 2 | 3 |
| 3 | 12 |
| 4 | 5 |
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:
textL = [10, 30, 50]
Then:
- position/index identifies where
- value tells you what is stored there
Do not confuse:
textindex = 2
with:
textvalue = 30
They are different concepts.
5. Accessing an item
Conceptually:
textL[i]
means:
value stored at positioni.
If:
textL = [4, 9, 2]
then some indexing convention might give:
textL[1] = 4
or:
textL[0] = 4
depending on the notation.
Again: follow the course pseudocode exactly.
6. Updating a list
A list can often be modified.
Example:
textL = [4, 9, 2]
Suppose second element becomes 7:
textL = [4, 7, 2]
Conceptually:
textL[position] = new_value
changes the stored state.
7. List as mutable state
Earlier CT weeks mostly updated variables such as:
textcount 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:
textfor each x in L: process x
or index-based iteration:
textfor i through valid positions: process L[i]
These are related but not identical.
9. Value iteration vs index iteration
Value iteration
textfor each x in L:
Useful when you only need the current value.
Index iteration
textfor 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:
textL = [7, 2, 4, 9]
length:
An empty list has length:
11. Empty list
Conceptually:
text[]
contains no elements.
Some algorithms require a nonempty list.
For example:
textmax = 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:
text7
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:
text7
before 9.
We must move:
text9
one position right:
text[2, 5, _, 9]
then place:
text7
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:
text2, 4, 7, 10
Descending:
text10, 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:
text5
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:
text3
Compare with:
text8.
Since:
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:
text5.
Compare backward.
With 8:
so shift 8:
text[3, 8, 8, 2]
Now compare with 3:
Stop shifting and place 5 after 3:
text[3, 5, 8, 2]
21. Insert fourth element
Current:
text[3, 5, 8 | 2]
Take:
text2.
Compare backward:
shift 8.
Then:
shift 5.
Then:
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:
23. Conceptual pseudocode
A standard insertion-sort structure is:
textfor 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:
text5.
If we immediately overwrite its position while shifting 8, we might lose 5.
So first:
textkey = 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:
textwhile previous_value > key:
shift previous value right.
Once:
textprevious_value <= key
stop.
27. Example with no shifting
Current sorted prefix:
text[2, 4, 6]
Next key:
text9
Since:
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:
text1
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−1
Total approximately:
Using:
the work grows roughly quadratically.
32. Complexity intuition
Insertion sort worst-case work is approximately:
while its best-case behavior on already sorted input can be roughly:
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:
textprevious > key
equal elements are not shifted past each other.
But if one unnecessarily shifts on:
textprevious >= 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:
textscore
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:
textoriginal → partially sorted → completely sorted
41. Trace table approach
For insertion sort, useful columns are:
| Pass | Key | Sorted prefix before | Shifts | List after |
|---|
Example:
Input:
text[6, 2, 4]
| Pass | Key | Prefix | Shifts | Result |
|---|---|---|---|---|
| 1 | 2 | [6] | 6 right | [2,6,4] |
| 2 | 4 | [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:
text7 → right 5 → right 4 → right
Then:
text[2, 4, 5, 7]
43. Sorted-prefix invariant
After inserting the element originally at position i:
This is the central correctness argument.
44. Why insertion sort works
Assume prefix is already sorted:
text[a₁, a₂, ..., aₖ]
Take new key:
textx
Shift every suffix element larger than x to the right.
Insert x after the last value:
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:
textL[i] = L[i-1]
before storing the original
L[i].You may destroy the value that must eventually be inserted.
Save:
textkey = L[i]
first.
Common mistake: shift in wrong direction
To make room for the key, larger elements move:
textright
not left.
Then the key occupies the newly created gap.
Common mistake: stop too early
Suppose:
text[2, 8, 10]
and key:
text5.
Comparing only against 10 is insufficient.
After shifting 10, compare against 8.
Since:
shift 8 too.
Stop only once correct insertion point is found.
Common mistake: move past beginning
When scanning backward, you need both:
- index/position is still valid
- previous value is greater than key
Conceptually:
textwhile 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:
textposition 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:
and must additionally satisfy the desired order.
These are the two conceptual requirements for sorting correctness:
- no elements lost/created
- 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:
textkey = 4
has already been safely stored.
If you forgot the key, you would have lost 4.
55. Ascending vs descending insertion sort
Ascending condition:
textshift while previous > key
Descending version:
textshift while previous < key
The algorithmic structure is the same; the comparison direction changes.
56. Finding insertion position
Another conceptual version:
- find correct position for key
- shift everything after that position
- 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:
textread 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:
text5 > 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:
text3
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:
For n=5:
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:
62. Selection connection
Every shift depends on a condition:
textprevious > 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:
textL = [9, 4, 7]
and an algorithm does:
textL[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:
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:
- Write the entire starting list.
- Mark the current sorted prefix.
- Store the current key separately.
- Trace each comparison.
- Write every shift.
- Insert the key.
- Update the sorted-prefix boundary.
- 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
textLIST │ ├── 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
textWeek 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:
- Explain what a list is.
- Distinguish index/position from stored value.
- Traverse a list.
- Trace list modifications.
- Understand insertion into a list.
- Explain the sorted-prefix idea.
- Trace insertion sort manually.
- Identify the current key.
- Understand why the key must be stored before shifting.
- Shift larger values to the right correctly.
- Determine the correct insertion position.
- Handle duplicate values.
- Understand why one element is trivially sorted.
- Explain the insertion-sort invariant.
- Recognize best-case nearly/already-sorted behavior.
- Recognize worst-case reverse-sorted behavior.
- Understand why worst-case work grows roughly like n2.
- 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)