Skip to content
ComputerCS
Start learning

Algorithms and Problem Solving · Lesson 3.6.1

Sorting Algorithms

Three classic sorts traced by hand — bubble, selection, insertion — plus the professional tools sorted() and key=.

01

Learning objectives

  • Trace bubble sort on a small list, showing the swaps of each pass.
  • Describe selection sort: select the smallest remaining value, place it at the front.
  • Describe insertion sort: slide each new element into the sorted part before it.
  • Distinguish sorted() (returns a new list) from .sort() (sorts in place).
  • Sort by a custom rule using key=, for example by length or by a record field.
02

Lesson notes

Sorting arranges a list into order, and it matters because order unlocks speed (binary search) and meaning (rankings, toppers, price lists). Python gives you sorted(data) for free, but the board expects you to trace the classics by hand, because they show how in-order is actually achieved — one comparison and one swap at a time. All three classics below share one idea: grow a sorted region until it swallows the whole list.

Bubble sort sweeps the list comparing neighbours; whenever the left one is bigger, they swap. After pass one, the largest value has bubbled to the last position; each later pass ignores one more settled element at the end. At most n − 1 passes finish the job. It is the easiest sort to trace — and among the slowest on big lists, which is exactly why it is a teaching sort.

Selection sort scans the unsorted part for the smallest value and swaps it into the front position, growing a sorted prefix one element per pass. Insertion sort takes the next element and slides it left into its correct place inside the already-sorted prefix — the way you arrange cards in your hand. Selection minimises swaps; insertion is fast when the list is already nearly sorted.

In practice you write two lines: ordered = sorted(data) returns a new sorted list and leaves the original untouched, while data.sort() rearranges the list in place and returns None — so y = data.sort() is a classic bug that quietly stores None in y. Both accept reverse=True for descending order. Choosing between them is a design decision: keep the original when you still need it, sort in place when memory or simplicity matters.

Both also accept key=, a function applied to every element before comparing: sorted(words, key=len) sorts by length instead of alphabetically, and with records, key=score_of ranks students by their score field. The sort is stable — equal keys keep their original relative order, which is why pear stays ahead of kiwi in the output below despite having the same length. Board tip: practise showing each bubble-sort pass as a row of lists; that trace table is the expected exam answer format.

Merge sort splits data into smaller groups before merging sorted halves.
Merge sort: split, sort and merge
03

Worked code examples

Bubble sort, complete

Each outer pass settles one more largest value at the end, so the inner sweep shortens by i each time. After the passes, order is complete.

def bubble_sort(nums):
    n = len(nums)
    for i in range(n - 1):
        for j in range(n - 1 - i):
            if nums[j] > nums[j + 1]:
                nums[j], nums[j + 1] = nums[j + 1], nums[j]
    return nums

print(bubble_sort([5, 1, 4, 2, 8]))
Output
[1, 2, 4, 5, 8]

sorted() versus .sort()

sorted() built a new list and left marks alone until .sort() rearranged it in place. The difference is invisible here but critical when the original order must survive.

marks = [72, 91, 66]
ordered = sorted(marks)
marks.sort()
print(ordered)
print(marks)
Output
[66, 72, 91]
[66, 72, 91]

Sorting by a rule with key=

key=len compares by word length; equal lengths (pear and kiwi) keep their original relative order because the sort is stable — pear was listed first.

words = ["pear", "fig", "apple", "kiwi"]
print(sorted(words))
print(sorted(words, key=len))
Output
['apple', 'fig', 'kiwi', 'pear']
['fig', 'pear', 'kiwi', 'apple']
04

Key terminology

bubble sort

Repeatedly comparing neighbours and swapping them if out of order, until no swap is needed.

selection sort

Finding the smallest remaining value and swapping it to the front, one position per pass.

insertion sort

Taking each new element and sliding it left into its place inside the sorted prefix.

in place

Rearranging the original list itself rather than building a new one — what .sort() does.

key function

A function passed as key= that each element is run through before comparing.

05

Common misconceptions

Common mistake

sorted(data) rearranges data itself.

Correct understanding

It returns a new sorted list and leaves data untouched. Only data.sort() changes the original.

Common mistake

y = data.sort() stores the sorted list in y.

Correct understanding

.sort() returns None, so y becomes None while data is silently sorted. Use y = sorted(data) instead.

Common mistake

Bubble sort is used in real systems because it is famous.

Correct understanding

It is famous as a teaching tool; its many swaps make it slow. Real systems use built-in sorts based on faster methods.

06

Check your understanding

1. The list [5, 1, 4, 2, 8] — what does it look like after ONE full pass of bubble sort?

2. data = [3, 1, 2]; y = data.sort(). What is y?

3. sorted(['bb', 'a', 'ccc'], key=len) gives —

NERDLYY · FEEDBACK

Help shape Nerdlyy

Your feedback goes directly to the team. We read every submission.

No reply needed — you can send feedback without sharing contact details.