5. Sorting
Opening
Big idea: Putting records in a useful order can make later work much easier.
Use a separate practice folder for the programs. Each example is self-contained unless its section says otherwise.
- Trace bubble, selection and insertion sort.
- Write complete implementations and test boundary cases.
- Compare growth rates, stability and storage behaviour.
Read the rule, trace the worked example, and try the quick check before reading its answers. When a result surprises you, change one input and explain the difference.
This is an original lesson following the listed syllabus topics. Examples, datasets, questions and diagrams were created for this edition.
The previous chapter stored waiting work in lines. This chapter arranges stored records in order. Both chapters care about sequence, but the goal changes from fair service to useful arrangement.
The chapter builds in stages. First the shared vocabulary: keys, order and preservation.
Then three sorting methods, each with its own worked trace. Then a comparison of their growth.
Each method reuses the same running input, so results stay comparable.
Study by tracing. Cover the expected output and predict it first. When a prediction fails, find the first line where your trace diverged. That line holds the lesson.
The running example is a set of five numbers. A class-marks program threads through every section, so each new method sorts the same familiar marks. Watch how the three methods reach the same answer by different routes.
Complete Python examples have Copy code and an external run link. First predict the output. Run the example, then change one input and explain what changed. The output box shows the expected result; it is not another program.
5.1 INTRODUCTION
Sorting changes arrangement. It should not invent records, lose records or remove repeated values. A result can look neatly ordered and still be wrong if some of the input disappeared.
The key tells you what “comes before” means. Sorting files by size differs from sorting them by label. Equal keys create another question: should those records keep their earlier relative order?
- Choose the key and ascending or descending direction.
- Check that every input record survives exactly as often as before.
- Check the required order and any rule for ties.
A notice board lists five marks in the order they arrived, and finding the middle mark takes a while.
Sorting rearranges records according to a chosen key. The key is the value used to compare records. One natural key here is the mark itself. A different task might sort the same records by name length instead.
Ascending order moves from smaller keys to larger keys. Descending order moves from larger keys to smaller keys.
The direction is part of the task, so state it before coding. A program that orders ascending has not solved a descending task.
A sort key decides what comes before what. Ascending means small to large.
The running input is five unsorted numbers. The sorted result keeps the same five numbers in ascending order. Nothing is added and nothing is lost.
| Before | After ascending sort |
|---|---|
| 26, 11, 19, 7, 14 | 7, 11, 14, 19, 26 |
Read the table. The left cell shows the starting order. The right cell shows the sorted order. Count the entries on both sides: five before and five after. Order changed, contents did not.
A correct sort must preserve the input records, including duplicate values. Returning only the smallest distinct values would fail even if that shortened result looked ordered.
A test should therefore compare multisets, not just admire the order.
A stable sort preserves the original relative order of records with equal keys. This matters when a list already carries a useful order.
Suppose three answer files tie on marks but arrived at different times. A stable sort by marks keeps the earlier arrival first among the tied files.
Write down what this program should print before you read the expected output.
records = [(85, "A"), (70, "B"), (85, "C")]
ordered = sorted(records, key=lambda r: r[0])
print(ordered)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores three records. Each record holds a mark and a tag. Files A and C tie on 85.
- Line 2 sorts by the mark only. The key function reads position zero of each record.
- Python sorting is stable, so the tie keeps arrival order. A stays before C.
- Line 3 prints the ordered list. B leads with 70, then the tied pair follows in arrival order.
[(70, 'B'), (85, 'A'), (85, 'C')]Change the first mark to 60. Predict the new printed order.
An in-place core uses only bounded extra working storage. Making a copy first adds storage even when the core algorithm is in-place.
The three functions in this chapter copy the input, so the caller keeps the original order. That copy costs storage proportional to the list length.
Try to predict the printed result first. The trace below explains every line.
marks = [72, 58, 91]
ordered = sorted(marks)
print(ordered)
print(marks)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores three marks in arrival order.
- Line 2 builds a new sorted list. The original list is untouched.
- Line 3 prints the new list in ascending order.
- Line 4 prints the original, still in arrival order. Copying protects the input but uses extra storage.
[58, 72, 91]
[72, 58, 91]Replace sorted(marks) with sorted(marks, reverse=True). Predict both printed lines.
The marks program threads through this chapter. Each sorting section will order the same five marks. The expected answer is always the same ascending list. Only the route changes.
Before running the program, say the output in your own words.
marks = [72, 58, 91, 64, 85]
print(sorted(marks))
print(len(marks))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores five marks in arrival order.
- Line 2 prints them sorted ascending. The smallest mark leads.
- Line 3 prints the count. Five marks entered and five marks remain. Preservation plus order is the full contract.
[58, 64, 72, 85, 91]
5Append 58 to the marks. Predict both printed lines, watching the duplicate.
Read the diagram. The first box fixes the comparison rule. The second box applies it pairwise. The third box guards the contents: no record may vanish. The last box checks the whole order, because one correct neighbour pair proves nothing alone.
Order plus preservation is the contract. Either half alone can look correct while failing.
Two files have equal sizes but different upload times. Why might stability matter?
Goal. Explain why the earlier file order among ties is worth keeping.
Approach. Ask what a size sort does to files whose sizes are equal.
Trace. A stable size sort keeps the earlier upload time first within each tied group. An unstable sort may reorder them without warning.
Result. Stability protects the earlier order among ties, rather than removing ties.
Result: Stability protects the earlier order among ties, rather than removing ties.
A program returns [7, 11, 14] for the input [11, 7, 14, 7]. Is it a correct sort?
Goal. Judge the output against both halves of the sorting contract.
Approach. Check the order first, then count each value.
Trace. The output is ordered, but the input holds two copies of 7 and the output holds one. A record vanished.
Result. The output fails preservation even though it looks ordered.
Result: No. The output is ordered but one copy of 7 is missing, so preservation fails.
5.2 BUBBLE SORT
Bubble sort looks at neighbouring values. If they are in the wrong order, it exchanges them. Repeating that small local action across the list moves a large value toward the right.
After a complete pass, the largest value in the active region has reached its final place. The next pass can ignore that finished position. The rest of the list may still need work.
- Compare the next adjacent pair.
- Swap only when the left value should come after the right.
- Finish the pass, mark the fixed rightmost position, and continue with the smaller region.
A leaderboard shows five scores in arrival order, and the organiser wants the highest score at the bottom of the screen.
Bubble sort compares each adjacent pair in the unsorted region. Adjacent means neighbours with nothing between them.
A comparison asks whether the left value should come after the right value. A swap exchanges the two values when the answer is yes.
Compare each adjacent pair from left to right. Swap when the left value is larger.
After a complete left-to-right pass, the largest value in that region has reached its final position at the right. The next pass can stop one position earlier.
A pass compares neighbours left to right. A swap fixes a wrongly ordered pair. The largest value sinks to the right end.
Here is why the largest value must end each pass at the right. Every time the large value meets a neighbour, the pair is wrongly ordered, so a swap moves it one step right.
Nothing can overtake it, because no value in the region is larger. It therefore travels to the end of the region.
Watch one full pass on the running input before studying the whole sort. Four neighbour comparisons, left to right, with the current list shown after each step.
Write down what this program should print before you read the expected output.
values = [26, 11, 19, 7, 14]
for j in range(4):
if values[j] > values[j + 1]:
values[j], values[j + 1] = values[j + 1], values[j]
print(values)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores the five running values.
- Lines 2 to 4 walk the four neighbour pairs. Pair one is 26 and 11: wrong order, so swap. The list becomes 11, 26, 19, 7, 14.
- Pair two is 26 and 19: wrong order, so swap. The list becomes 11, 19, 26, 7, 14.
- Pair three is 26 and 7: wrong order, so swap. The list becomes 11, 19, 7, 26, 14.
- Pair four is 26 and 14: wrong order, so swap. The largest value 26 finishes at the right.
- Line 5 prints the list after this single pass. Only the last position is guaranteed final.
[11, 19, 7, 14, 26]Start from [14, 7, 19, 11, 26] instead. Predict the printed list after one pass.
Read the diagram. The first two boxes repeat for every neighbour pair in the pass. The third box marks the achievement: the right end now holds its final value. The last box shrinks the next region, because rechecking a finished position wastes work.
The full sort repeats such passes on a shrinking region. Each row below is the list after one complete pass. Read down the right column and watch the sorted suffix grow from the right.
| Pass | Array after the pass |
|---|---|
| 1 | 11, 19, 7, 14, 26 |
| 2 | 11, 7, 14, 19, 26 |
| 3 | 7, 11, 14, 19, 26 |
| 4 | 7, 11, 14, 19, 26 |
Read the table. Pass one moves 26 to the far right in four swaps. Pass two moves 19 next to it. Pass three moves 14 into place. Pass four makes no swap, which proves the list is sorted. The last two rows share the same list because the final pass only checks.
A program can even print how many swaps each pass made. The verified output below lists the four pass counts in order. Their sum is the total swap count for this input.
Try to predict the printed result first. The trace below explains every line.
a = [26, 11, 19, 7, 14]
for end in range(4, 0, -1):
swaps = 0
for j in range(end):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
swaps += 1
print(swaps)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Lines 1 and 2 set up the list and the shrinking end marker. Pass one uses end 4, so four pairs.
- The inner loop swaps four times: 26 sinks past every smaller value. The first print shows 4.
- Pass two uses end 3. Two swaps move 19 into place beside 26.
- Pass three uses end 2. One swap moves 14 into place.
- Pass four uses end 1. Zero swaps, so the list is sorted. The prints add to 7 total swaps.
4
2
1
0Run the same counter on [7, 11, 14, 19, 26]. Predict the four printed numbers.
The pass comparison counts are 4, 3, 2 and 1. They add to 10, which matches the recorded trace count of 10 comparisons. Show the addition; do not trust a bare total.
Predict the output before running this complete example.
def bubble_sort(values):
a = values.copy()
for end in range(len(a) - 1, 0, -1):
changed = False
for j in range(end):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
changed = True
if not changed:
break
return a
print(bubble_sort([26,11,19,7,14]))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- The function first copies the input, so its caller keeps the original list.
- The inner loop compares neighbours and swaps an out-of-order pair.
- The largest remaining value moves to the end of the active region.
- A whole pass with no change means the list is already ordered.
[7, 11, 14, 19, 26]Pass an already ordered list and follow the early-stop condition.
Line 1 copies the input, so the caller keeps the original order. The outer loop shrinks the end marker. The inner loop walks the neighbour pairs. The strict greater-than comparison decides every swap.
The changed flag permits an early stop when a pass makes no swap. No swap means no pair was wrongly ordered, which means the whole list is sorted. Later passes would only recheck a sorted list.
Read the diagram. The first box is the observation: a full pass with zero swaps. The second box states what that observation proves. The last two boxes give the reward: stop now and skip the remaining passes.
The strict comparison keeps equal-key items unswapped, so this adjacent-swap version is stable. Equal neighbours never exchange, which preserves their arrival order.
Stability here comes from the strict sign, not from the name of the algorithm.
Before running the program, say the output in your own words.
def bubble_sort(values):
a = values.copy()
passes = 0
for end in range(len(a) - 1, 0, -1):
passes += 1
changed = False
for j in range(end):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
changed = True
if not changed:
break
return a, passes
print(bubble_sort([7, 11, 14, 19, 26]))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Lines 1 to 3 copy the input and start a pass counter.
- Lines 4 to 12 run passes with the early-stop flag. The input is already ordered, so the first pass compares four pairs and swaps nothing.
- Line 5 counts this first pass. The flag stays false, so the break runs at once.
- Line 14 prints the pair: the unchanged sorted list and 1 pass. An ordered list of five costs only four checks here.
([7, 11, 14, 19, 26], 1)Sort [26, 19, 14, 11, 7] with the same counter. Predict the printed pair.
The marks program returns with bubble sort. The same five marks, the same expected ascending list, now reached by neighbour swaps.
Write down what this program should print before you read the expected output.
def bubble_sort(values):
a = values.copy()
for end in range(len(a) - 1, 0, -1):
changed = False
for j in range(end):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
changed = True
if not changed:
break
return a
print(bubble_sort([72, 58, 91, 64, 85]))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Lines 1 to 12 define bubble sort exactly as above. Definitions alone sort nothing.
- Line 14 calls the function on the five marks. Pass one sinks 91 to the right end. Later passes sink 85, then 72.
- The printed list is ascending. It matches the section 5.1 answer, reached by a different route.
[58, 64, 72, 85, 91]Append 100 to the marks. Predict the printed list.
For this input the trace uses 10 key comparisons. That is a measurement of this exact variant and input, not a universal number for every bubble sort.
Always report the input, the variant and the counting rule beside any count.
One full pass fixes one end position. The suffix on the right is final; the rest may still be unsorted.
Predict the list after one bubble pass on [26, 11, 19, 7, 14].
Goal. State the list after the first left-to-right pass.
Approach. Walk the four neighbour pairs and swap each wrongly ordered pair.
Trace. 26 sinks past 11, 19, 7 and 14 in four swaps. Each swap moves 26 one step right.
Result. Only the last position is guaranteed final after one pass.
Result: [11, 19, 7, 14, 26]. The largest value 26 reaches the far right.
A student claims the list is sorted after two bubble passes on the running input. Check the claim.
Goal. Test whether two passes finish the running input.
Approach. Read the pass table rows for passes one and two.
Trace. After two passes the list is [11, 7, 14, 19, 26]. The pair 11 and 7 is still wrongly ordered.
Result. The claim fails on the very first pair of the remaining region.
Result: False. Two passes leave [11, 7, 14, 19, 26], which is not sorted.
This version never finishes early. Name the missing piece and its effect.
Goal. Find why the sort cannot stop on an ordered list.
Approach. Compare the loops with the taught version line by line.
Trace. The changed flag and its break test are absent. Every input therefore runs all four passes.
Result. Ordered inputs pay the full pass count instead of stopping after one check pass.
Result: Add the changed flag, set it on each swap, and break when a pass makes no swap.
5.3 SELECTION SORT
Selection sort first searches the unsorted region for its smallest value. It remembers that value’s position. Only after the scan does it place the winner at the next position in the sorted prefix.
The remembered position may change several times during a scan. That does not mean you have to move records each time. Separating selection from movement makes the algorithm easier to trace.
- Start with a candidate minimum in the unsorted region.
- Scan the rest and update the candidate when a smaller value is found.
- Swap the chosen minimum into the next prefix position.
A teacher scans five answer piles to award the lowest mark first, then repeats for the next lowest.
Selection sort searches the unsorted region for its smallest value before moving anything. The search remembers the position of the best candidate seen so far.
Only after the scan finishes does one swap place the winner.
At each position, scan the remaining region and remember the index of its smallest value. Swap that value into the current position.
The sorted prefix grows from the left. The scan must finish before the selection is known, because a later entry might be smaller.
Selection scans first and moves once. The growing left prefix is final.
Watch the first scan on the running input. The candidate index changes only when a strictly smaller value appears. Nothing moves until the scan ends.
Try to predict the printed result first. The trace below explains every line.
values = [26, 11, 19, 7, 14]
smallest = 0
for j in range(1, 5):
if values[j] < values[smallest]:
smallest = j
print(smallest)
print(values[smallest])Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores the five running values. Line 2 assumes index 0 holds the minimum.
- Index 1 holds 11, smaller than 26, so the candidate moves to 1.
- Index 2 holds 19, not smaller than 11, so the candidate stays.
- Index 3 holds 7, smaller than 11, so the candidate moves to 3.
- Index 4 holds 14, not smaller than 7, so the candidate stays. The scan ends with index 3.
- The prints show the winning index and its value 7. One swap will now place it first.
3
7Start from [19, 26, 11, 14, 7] instead. Predict the printed index and value.
Read the diagram. The first box sets the opening candidate. The second box is the whole scan: compare and update, never move. The third box performs the single swap. The last box records progress: one more prefix position is final.
The full sort repeats this scan-and-place step. Each row below is the list after one placed minimum. Read the left prefix: it only grows, and it never changes again.
| Pass | Array after the pass |
|---|---|
| 1 | 7, 11, 19, 26, 14 |
| 2 | 7, 11, 19, 26, 14 |
| 3 | 7, 11, 14, 26, 19 |
| 4 | 7, 11, 14, 19, 26 |
Read the table. Pass one places 7 first. Pass two finds 11 already in place, so the swap changes nothing visible. Pass three places 14. Pass four places 19. An unchanged row is normal: the scan confirmed the value instead of moving a new one.
A program can print the winning index and value of every pass. The verified output below shows all four selections in order. The second line proves the self-placement: index 1 already held 11.
Before running the program, say the output in your own words.
a = [26, 11, 19, 7, 14]
for start in range(4):
m = start
for j in range(start + 1, 5):
if a[j] < a[m]:
m = j
print(m, a[m])
a[start], a[m] = a[m], a[start]Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Lines 1 and 2 copy the list and open the first scan at index 0. The inner loop finds 7 at index 3.
- Line 7 prints the winner: index 3 holding 7. Line 8 swaps it into position 0.
- The second scan starts at index 1. No smaller value appears later, so it prints 1 and 11, then swaps the entry with itself.
- The third scan prints 4 and 14, placing 14 at index 2. The fourth scan prints 4 and 19, placing 19 at index 3.
3 7
1 11
4 14
4 19Run the same printer on [72, 58, 91, 64, 85]. Predict the first printed line.
Predict the output before running this complete example.
def selection_sort(values):
a = values.copy()
for start in range(len(values) - 1):
smallest = start
for j in range(start + 1, len(values)):
if a[j] < a[smallest]:
smallest = j
a[start], a[smallest] = a[smallest], a[start]
return a
print(selection_sort([26,11,19,7,14]))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Start marks the next position to be fixed.
- Smallest remembers an index, not a separate copy of the value.
- The scan updates that index whenever a smaller candidate is found.
- After the scan, one swap places the chosen minimum into its final prefix position.
[7, 11, 14, 19, 26]Try repeated values and identify the difference between comparing values and tracking record identity.
Lines 1 to 2 copy the input. The outer loop fixes each prefix position in turn. The inner loop scans the rest and tracks the smallest index. The single swap after the inner loop does the only moving.
This input uses 10 key comparisons. The simple implementation scans each remaining region even when the list is already ordered, so its comparison count is quadratic in the list length.
An ordered input costs just as much as a shuffled one.
Write down what this program should print before you read the expected output.
def selection_sort_count(values):
a = values.copy()
comparisons = 0
for start in range(len(a) - 1):
smallest = start
for j in range(start + 1, len(a)):
comparisons += 1
if a[j] < a[smallest]:
smallest = j
a[start], a[smallest] = a[smallest], a[start]
return comparisons
print(selection_sort_count([7, 11, 14, 19, 26]))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Lines 1 to 3 copy the list and start a comparison counter.
- The loops repeat the taught scan exactly, adding one to the counter per pair checked.
- No early stop exists: the scans run 4, 3, 2 and 1 checks even on ordered input.
- The print shows 10. Order in the input does not reduce this count.
10Count the same way on [26, 19, 14, 11, 7]. Predict the printed number.
The marks program returns with selection sort. The scans find 58, then 64, then 72, then 85, placing each in turn.
Try to predict the printed result first. The trace below explains every line.
def selection_sort(values):
a = values.copy()
for start in range(len(values) - 1):
smallest = start
for j in range(start + 1, len(values)):
if a[j] < a[smallest]:
smallest = j
a[start], a[smallest] = a[smallest], a[start]
return a
print(selection_sort([72, 58, 91, 64, 85]))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Lines 1 to 9 define selection sort exactly as above.
- Line 11 calls the function on the five marks. Each scan selects the smallest remaining mark.
- The printed list matches the bubble result from section 5.2. Same answer, different route.
[58, 64, 72, 85, 91]Sort the marks in descending order by changing the comparison. Predict the printed list.
Selection sort makes relatively few swaps, but the usual distant swap can move one equal-key record past another. It is therefore not generally stable.
A stability claim must describe the actual implementation, not merely the algorithm name.
Watch a distant swap break a tie. Two records share mark 85. The minimum scan selects index 2, and the swap with index 0 carries the later record past the earlier one.
Before running the program, say the output in your own words.
a = [(85, "A"), (85, "C"), (70, "B")]
smallest = 0
for j in range(1, 3):
if a[j][0] < a[smallest][0]:
smallest = j
a[0], a[smallest] = a[smallest], a[0]
print(a)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores three records. A and C tie on 85 with A first.
- Lines 2 to 5 scan the marks. Index 1 ties but the strict sign keeps the candidate. Index 2 holds 70, so the candidate moves there.
- Line 6 swaps index 0 with index 2. The 70 record lands first, which is correct.
- But C now precedes A although A arrived first. The distant swap reversed the tied pair. The print proves the instability.
[(70, 'B'), (85, 'C'), (85, 'A')]Use <= in the scan instead. Predict whether the printed order changes.
Never swap during the scan if you intend the taught variant. Remember the best candidate and swap once per pass.
Scan fully, then move once. The prefix on the left is final; the rest is merely waiting for later selections.
Predict the list after one selection pass on [26, 11, 19, 7, 14].
Goal. State the list after the first scan-and-swap.
Approach. Scan all five values, remember the smallest index, then swap once.
Trace. The scan finds 7 at index 3. Swapping with index 0 gives [7, 11, 19, 26, 14].
Result. Only the first position is guaranteed final after one pass.
Result: [7, 11, 19, 26, 14]. The scan selects 7, then one swap places it first.
A student swaps every time a smaller value appears during the scan. What goes wrong?
Goal. Explain why moving during the scan breaks the taught method.
Approach. Ask what the scan assumes about the region it has not read yet.
Trace. An early swap disturbs positions the scan still needs to compare. The remembered index may then point at a moved value.
Result. The result can still end sorted, but extra swaps occur and the trace no longer matches selection sort.
Result: Keep the scan read-only and swap once after it. Extra mid-scan swaps add movement without adding information.
Is the shown selection sort stable? Use the tied-records demo as evidence.
Goal. Judge stability from an actual tied run.
Approach. Check whether the tied pair keeps arrival order after sorting by marks.
Trace. A arrived before C, but the printed order shows C before A. The distant swap with the 70 record caused it.
Result. The implementation is not stable, as the printed tie order proves.
Result: No. The demo prints C before A although A arrived first, so stability fails.
5.4 INSERTION SORT
Imagine holding a small ordered set of cards. When the next card arrives, you move larger cards aside until there is a gap where it belongs. The same idea gives insertion sort.
Keep a copy of the incoming key before shifting. Otherwise the first shift can overwrite the value you were trying to insert. The shifting loop changes positions, while the saved key remains available.
- Assume the earlier prefix is already sorted.
- Save the next value and shift larger prefix values to the right.
- Place the saved value in the gap and extend the sorted prefix.
A player holds four ordered cards and picks up a fifth card that belongs somewhere in the middle.
Insertion sort places each new value into a prefix that is already ordered. The prefix starts as the single first entry, which needs no sorting. Each step takes the next entry and inserts it where it belongs.
Save the next value as the key. Move larger prefix values one place to the right until the insertion position is available, then put the saved key there. After the step, the prefix includes one more ordered entry.
Save the key, shift larger values right, then place the key in the gap.
Here is why the key must be saved first. Each shift copies a prefix value one place right, overwriting whatever sat there.
Without a saved copy, the new value would be destroyed by the first shift. The saved key survives while positions move around it.
Watch one insertion into an ordered prefix. The key 14 enters [11, 19, 26]. Two larger values shift right, then the key lands in the freed gap.
Write down what this program should print before you read the expected output.
a = [11, 19, 26, 14, 30]
key = a[3]
j = 2
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
print(a)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores the list. The first three entries are already ordered.
- Line 2 saves the key 14 before any shifting. Lines 3 to 6 open the scan at the prefix end.
- First check: 26 exceeds 14, so 26 shifts right and j steps back.
- Second check: 19 exceeds 14, so 19 shifts right and j steps back.
- Third check: 11 does not exceed 14, so the loop stops with j at 0.
- Line 7 writes the saved key at position 1. The print shows the gap correctly filled.
[11, 14, 19, 26, 30]Insert 20 into [11, 14, 19, 26, 30] the same way. Predict the printed list.
Read the diagram. The first box protects the new value. The second box makes room by shifting, never by swapping pairs. The third box fills the gap with the saved key. The last box extends the ordered prefix by exactly one entry.
The full sort repeats this insertion for every later entry. Each row below is the list after one more entry joins the ordered prefix. Read the growing ordered block from the left.
| Pass | Array after the pass |
|---|---|
| 1 | 11, 26, 19, 7, 14 |
| 2 | 11, 19, 26, 7, 14 |
| 3 | 7, 11, 19, 26, 14 |
| 4 | 7, 11, 14, 19, 26 |
Read the table. Inserting 11 shifts 26 aside. Inserting 19 shifts only 26. Inserting 7 shifts 26, 19 and 11, the longest move. Inserting 14 shifts 26 and 19. The prefix after each row is ordered.
A program can count the shifts each insertion performs. The verified output below lists the four shift counts in order. Compare them with the comparison counts: shifting and comparing are different work.
Try to predict the printed result first. The trace below explains every line.
a = [26, 11, 19, 7, 14]
for i in range(1, 5):
key = a[i]
j = i - 1
shifts = 0
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
shifts += 1
a[j + 1] = key
print(shifts)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Lines 1 to 3 set up the list and save each key before shifting.
- Inserting 11 shifts 26 once. The first print shows 1.
- Inserting 19 shifts 26 once. The prefix 11 stays.
- Inserting 7 shifts 26, 19 and 11: three moves, the longest insertion.
- Inserting 14 shifts 26 and 19, then stops at 11. The prints add to 7 shifts.
1
1
3
2Count the shifts the same way on [72, 58, 91, 64, 85]. Predict the four printed numbers.
The four insertions compare 1, 2, 3 and 3 times, adding to 9. That matches the recorded trace count of 9 key comparisons. Loop-bound checks are not included in this counting rule.
Predict the output before running this complete example.
def insertion_sort(values):
a = values.copy()
for i in range(1, len(values)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return a
print(insertion_sort([26,11,19,7,14]))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- The prefix before i is already sorted.
- Key saves the next value before any shifting overwrites its old position.
- Larger prefix entries move right until the insertion gap is found.
- Writing key into that gap makes the sorted prefix one entry longer.
[7, 11, 14, 19, 26]Start with an almost sorted list and count how many values actually need shifting.
Lines 1 to 2 copy the input. The loop starts at index 1 because a lone first entry is already ordered.
The inner loop shifts larger values right and stops at the first value that is not larger. The final line places the saved key.
The key must be saved before shifting, otherwise it can be overwritten. The strict comparison shifts only larger values, preserving the order of equal keys.
Equal values never move past each other, so this version is stable.
The marks program returns with insertion sort. Each new mark inserts into the ordered prefix: 58 before 72, 91 at the end, 64 between 58 and 72, 85 between 72 and 91.
Before running the program, say the output in your own words.
def insertion_sort(values):
a = values.copy()
for i in range(1, len(values)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return a
print(insertion_sort([72, 58, 91, 64, 85]))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Lines 1 to 10 define insertion sort exactly as above.
- Line 12 calls the function on the five marks. The prefix grows: 72, then 58 with 72, then 91 at the end, then 64 inserted, then 85 inserted.
- The printed list matches both earlier methods. Three routes, one answer.
[58, 64, 72, 85, 91]Insert 77 into the marks first, then sort. Predict the printed list.
Insertion sort performs well on small or nearly ordered lists because relatively few shifts may be needed. On an ordered list of five it checks only four keys, one per insertion.
The next section measures exactly this difference.
Shifting makes room; the saved key fills it. Never let a shift overwrite the value being inserted.
Predict the list after two insertion steps on [26, 11, 19, 7, 14].
Goal. State the list after inserting 11 and then 19.
Approach. Treat the first entry as an ordered prefix and insert each next key.
Trace. Inserting 11 shifts 26 aside: [11, 26, 19, 7, 14]. Inserting 19 shifts 26 aside: [11, 19, 26, 7, 14].
Result. The first three entries are ordered; the rest are untouched.
Result: [11, 19, 26, 7, 14]. Each insertion extends the ordered prefix by one.
A version drops the key variable and compares a[i] inside the shifting loop. What breaks?
Goal. Explain why the new value must be saved before shifting.
Approach. Ask what the first shift overwrites.
Trace. The first shift copies a larger value into position i, destroying the original a[i]. Later comparisons then read the shifted value, not the intended key.
Result. The inserted value is lost and the output is wrong.
Result: Save the key first. The loop must compare the saved copy, because shifts overwrite list positions.
Why does the strict sign keep this insertion sort stable?
Goal. Connect the comparison sign to the fate of equal keys.
Approach. Ask whether an equal prefix value shifts or stays.
Trace. With a strict sign, an equal value does not shift, so the new key lands after its equals. Arrival order among ties is preserved.
Result. Equal keys never cross, which is exactly the stability promise.
Result: The strict sign leaves equal values in place, so each new key settles after its equals.
5.5 TIME COMPLEXITY OF ALGORITHMS
A small list can make many algorithms look equally fast. To compare them, ask what extra work appears when the input grows. Count a meaningful operation, such as comparing two keys.
An already sorted input and a reverse-sorted input may cause different amounts of work. State which case you are discussing. A growth class explains a trend; it does not claim an exact runtime on every computer.
- Define the input size and the operation being counted.
- Describe the best, typical or worst input conditions.
- Compare growth while keeping preparation, copying and implementation details in view.
One timing on five marks says nothing about a library with thousands of records.
Time complexity describes how work grows with input size. Choose a basic operation, such as a key comparison, and define the case being considered.
Best, average and worst cases can differ. Counting needs all three choices stated: size, operation and case.
Fix the operation first. This section counts key comparisons between list values.
Index arithmetic and loop-bound checks are not counted. A different rule would give different numbers, so comparisons across sources need the same rule.
Growth analysis fixes the size, the operation and the case, then counts.
Read the diagram. The first box sets the measurement frame. The next two boxes count opposite extremes: the kindest input and the cruellest input. The last box draws the lesson: compare trends across sizes, not stopwatch seconds on one run.
Best and worst inputs are concrete here. An ordered list of five is kind to bubble and insertion sort. A reversed list is cruel to all three simple methods. Selection sort scans fully in both cases.
Write down what this program should print before you read the expected output.
def bubble_count(values):
a = values.copy()
comparisons = 0
passes = 0
for end in range(len(a) - 1, 0, -1):
passes += 1
changed = False
for j in range(end):
comparisons += 1
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
changed = True
if not changed:
break
return passes, comparisons
print(bubble_count([7, 11, 14, 19, 26]))
print(bubble_count([26, 19, 14, 11, 7]))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Lines 1 to 3 copy the list and start two counters.
- The loops repeat the taught bubble sort with the early-stop flag.
- On the ordered list, the first pass compares 4 pairs and swaps nothing, so the break runs at once. The first print shows one pass and four comparisons.
- On the reversed list, every pass swaps, so all four passes run. The comparisons add to 10.
- Same program, same size, different order: 4 checks against 10. Order matters for this variant.
(1, 4)
(4, 10)Count the same way on [11, 7, 14, 19, 26]. Predict the printed pair.
The table below measures all three methods on three inputs of five entries. Every number comes from the same counting rule and the same size. Read across each row to see which method reacts to order.
| Input of five entries | Bubble | Selection | Insertion |
|---|---|---|---|
| Already ordered | 4 | 10 | 4 |
| Running input | 10 | 10 | 9 |
| Reversed | 10 | 10 | 10 |
Read the table. The selection column never moves: ten checks in every row, because its scans ignore order. The bubble column drops to four on ordered input thanks to the early stop. The insertion column drops to four on ordered input because each key stops at once. The cruel row is identical: ten everywhere.
Big-O gives an asymptotic upper bound on growth; it is not a stopwatch prediction. Saying an algorithm is quadratic means its counted work grows like the square of the size for large inputs.
It does not state seconds, and it hides constant factors such as copying and memory layout.
| Algorithm variant | Best comparison growth | Worst comparison growth |
|---|---|---|
| Bubble with early stop | Linear | Quadratic |
| Simple selection | Quadratic | Quadratic |
| Insertion with strict shifts | Linear | Quadratic |
Read the table. Best and worst follow the measured pattern above. Bubble and insertion improve on kind inputs; their cruel inputs still grow quadratically. Selection grows quadratically in both columns. Growth class is a trend statement, not a timing.
For simple selection sort, the comparisons form a descending sum. For a list of length n, it is n(n - 1) / 2.
A list of eight needs 4 + 3 + 2 + 1 + 7 + 6 + 5 checks grouped either way: twenty-eight. Show the addition before quoting the total.
For routine Python applications, the built-in sort is normally preferable to rewriting a teaching algorithm. The library routine is implemented in a lower-level language and handles edge cases the teaching versions ignore.
Study these three methods to understand sorting, then use the library to sort.
Comparison counts rise much faster for simple selection sort than a linear reference as list length grows.
Read the figure. The horizontal axis is the list length: 4, 8, 16 and 32. The vertical axis counts operations. The selection curve bends upward steeply while the linear reference climbs steadily. The gap between them is the visual meaning of quadratic against linear growth.
Find the comparison count for simple selection sort on 16 entries.
Add the sizes of the successive scans, or use the stated sum formula.
Result: 120 key comparisons.
An ordered list of five costs bubble sort four comparisons but selection sort ten. Explain the difference.
Goal. Explain why order helps one method and not the other.
Approach. Ask what each method does after finding no disorder.
Trace. Bubble sort observes a swap-free pass and stops after four checks. Selection sort has no such observation, so it completes all ten scans.
Result. The early stop converts an observation into saved work; without it, the scans run regardless.
Result: Bubble sort stops after its evidence pass, while simple selection sort cannot recognise an ordered input.
Test all implementations on an empty list, one entry, duplicates, an already sorted list and reverse order. For routine Python applications, built-in sorting is normally preferable to rewriting a teaching algorithm.
State the size, the operation and the case before quoting any count. Without that frame, two correct-looking numbers can disagree for honest reasons.
Summary
Use these points to test what you can explain without looking back.
- Sorting uses a key and must preserve every record, including duplicates.
- Ascending moves small to large; descending reverses the comparison direction.
- A stable sort keeps arrival order among equal keys; the shown bubble and insertion variants are stable.
- Ordinary distant-swap selection sort is not generally stable, as the tied-records demo proves.
- Bubble sort fixes a suffix through adjacent swaps; one pass fixes one right-end position.
- The changed flag stops bubble sort after a swap-free pass, which costs little on ordered input.
- Selection sort fixes a prefix by scanning fully, then swapping once per pass.
- Simple selection sort compares the same count whether the input is ordered or not.
- Insertion sort expands a sorted prefix by saving a key, shifting larger values, and placing the key.
- The key must be saved before shifting, and the strict sign keeps equal keys unmoved.
- Shifting one place differs from swapping a pair; the saved key moves only into its gap.
- Report the input, the algorithm variant, the case and the counting rule with every count.
- Test empty lists, single entries, duplicates, ordered and reversed inputs before trusting a sort.
- For routine work, prefer the built-in sort; study these three methods to understand sorting.
Exercise
Work independently. For a program, predict the result before running it. Explain your reasoning as well as giving an answer.
5.1 State the two halves of the sorting contract in your own words.
5.2 Predict the list after one bubble pass on the running input, then name the guaranteed position.
Try to predict the printed result first. The trace below explains every line.
values = [26, 11, 19, 7, 14]
for j in range(4):
if values[j] > values[j + 1]:
values[j], values[j + 1] = values[j + 1], values[j]
print(values)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores the five running values.
- Each loop step compares one neighbour pair and swaps when the left value is larger.
- The value 26 swaps four times and reaches the far right.
- Only the last position is guaranteed final after one pass.
[11, 19, 7, 14, 26]Start from [19, 26, 11, 14, 7] and predict the printed list.
5.3 Give the full selection pass table for the running input.
5.4 Give the list after two insertion steps on the running input.
5.5 This bubble pass crashes. Name the faulty line and give the repair.
a = [26, 11, 19, 7, 14]
for j in range(5):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]5.6 This selection scan moves during the scan. Explain the fault and give the repair.
for start in range(len(a) - 1):
for j in range(start + 1, len(a)):
if a[j] < a[start]:
a[start], a[j] = a[j], a[start]5.7 This insertion loses the new value. Explain the fault and give the repair.
for i in range(1, len(a)):
j = i - 1
while j >= 0 and a[j] > a[i]:
a[j + 1] = a[j]
j -= 1
a[j + 1] = a[i]5.8 Write a bubble sort that orders descending, and show its result on the marks.
5.9 Write a stability test with tied marks and state the verdict for the shown selection sort.
5.10 How many comparisons does simple selection sort use for 8 entries?
5.11 Bubble sort checks four pairs on one ordered list of five and ten on a reversed one. Explain both numbers.
5.12 Insertion sort checks four keys on an ordered list of five but ten on a reversed one. Explain both numbers.
5.13 Contrast the three methods by stating which end becomes final first in each.
5.14 Would the shown copy-returning functions change the caller’s original list? How would you write a truly in-place version?
5.15 A sort returns ordered output but drops one duplicate mark. Which test catches this, and why?
5.16 Predict the full output of this marks program, then explain each printed line.
Try to predict the printed result first. The trace below explains every line.
marks = [72, 58, 91, 64, 85]
print(sorted(marks))
print(len(marks))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores five marks in arrival order.
- Line 2 prints them in ascending order. The smallest mark leads.
- Line 3 prints the count. Five marks entered and five marks remain, so preservation holds.
[58, 64, 72, 85, 91]
5Append 58 and predict both printed lines, watching the duplicate.
Answers
5.1 Order the records by the key, and preserve every record including duplicates.
5.2 [11, 19, 7, 14, 26]. Only the final position is guaranteed after one pass.
5.3 7, 11, 19, 26, 14, then 7, 11, 19, 26, 14, then 7, 11, 14, 26, 19, then 7, 11, 14, 19, 26.
5.4 11, 19, 26, 7, 14. The prefix [11, 19, 26] is ordered; the rest is untouched.
5.5 range(5) reaches j = 4, and a[5] does not exist. Use range(4), or range(end) with end = len(a) - 1, so the last comparison reads a[4] against nothing beyond it.
5.6 It swaps mid-scan instead of tracking the smallest index and swapping once after the scan. Keep a smallest index, update it on a smaller value, and swap once after the inner loop.
5.7 It reads a[i] after shifts may have overwritten position i. Save key = a[i] before the loop, compare against key, and write key into the gap.
5.8 The printed list is descending: [91, 85, 72, 64, 58]. Every comparison is reversed, so larger values bubble left instead.
Before running the program, say the output in your own words.
def bubble_sort(values):
a = values.copy()
for end in range(len(a) - 1, 0, -1):
changed = False
for j in range(end):
if a[j] < a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
changed = True
if not changed:
break
return a
print(bubble_sort([72, 58, 91, 64, 85]))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Lines 1 to 12 define bubble sort with the comparison reversed to <.
- Line 14 calls it on the five marks. Smaller values now sink right, larger values rise left.
- The printed list is fully descending. The trace and pass structure match the ascending version.
[91, 85, 72, 64, 58]Sort the running input descending the same way and predict the printed list.
5.9 Tags on equal marks expose the order change. The shown selection sort prints C before A, so it fails the stability test.
Write down what this program should print before you read the expected output.
a = [(85, "A"), (85, "C"), (70, "B")]
smallest = 0
for j in range(1, 3):
if a[j][0] < a[smallest][0]:
smallest = j
a[0], a[smallest] = a[smallest], a[0]
print(a[1][1], a[2][1])Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores two tied records, A before C, plus a smaller record.
- Lines 2 to 5 select the smallest mark, index 2.
- Line 6 swaps it into position 0, carrying C past A.
- Line 7 prints the tied tags in their new order: C before A. Stability fails.
C ARepeat the test with the shown bubble sort on the tied pair and predict the printed tags.
5.10 28. The scans add 7 + 6 + 5 + 4 + 3 + 2 + 1.
5.11 Ordered input stops after one swap-free pass of four checks. Reversed input swaps every pass, so all 4 + 3 + 2 + 1 checks run.
5.12 Each insertion into an ordered prefix stops after one check, giving four. Each insertion into a reversed prefix shifts everything, giving 1 + 2 + 3 + 4.
5.13 Bubble fixes the right end each pass. Selection fixes the left prefix each pass. Insertion grows an ordered left prefix each step.
5.14 No. Each starts from a copy. Sort the supplied list directly and return nothing, documenting that the input order is destroyed.
5.15 A count-preservation test: compare the multiset of values, or the length plus each multiplicity, before and after sorting.
5.16 [58, 64, 72, 85, 91] and 5. Sorting orders the marks while the length check confirms that nothing was lost.