Module 7 · Sorting · Lesson 23 of 40
Simple sorts: bubble, selection and insertion
Three easy-to-understand sorting methods, how they work step by step, and why they are O(n²).
In this lesson · about 25 minutes
- Explain how bubble, selection and insertion sort work
- Say what stable and in-place mean
- Know when a simple sort is good enough
Sorting puts items in order, like smallest to biggest. Sorted data makes many jobs easier: binary search, finding duplicates, finding the median. Let's start with three simple methods.
Bubble sort
Walk through the list comparing neighbours. If a pair is in the wrong order, swap it. After one pass, the biggest value has "bubbled" to the end. Repeat for the rest. If a pass makes no swaps, the list is sorted and you can stop early.
Selection sort
Find the smallest value and swap it to the front. Then find the smallest of the rest and put it second. And so on. It always does the same number of comparisons, even on a sorted list.
Insertion sort
This is how most people sort playing cards. Take the next card and slide it left into its place among the cards you already sorted. On a list that is nearly sorted, very little sliding is needed, so it is fast.
Try it · see it work
Sorting visualizer
Try Bubble, Selection and Insertion on the same list. Compare their comparison counts. Then press Shuffle.
Comparisons so far: 0
Step 1 of 33Start: [5, 2, 8, 1, 9, 3, 7, 4].
Words to know
- In-place: sorts inside the same list, using only O(1) extra memory. All three simple sorts are in-place.
- Stable: items with equal values keep their original order. Bubble and insertion are stable; selection is not (a long-distance swap can jump over an equal item).
- Adaptive: faster when the input is already nearly sorted. Bubble (with early stop) and insertion are adaptive.
| Sort | Best | Average / worst | Stable? |
|---|---|---|---|
| Bubble | O(n) if already sorted | O(n²) | Yes |
| Selection | O(n²) | O(n²) | No |
| Insertion | O(n) if already sorted | O(n²) | Yes |
All three are O(n²) in the worst case: fine for small lists (a few hundred items) or nearly-sorted data, too slow for big data.
Try it: insertion sort with a printout
Exercise
Write bubble sort
Write bubble_sort(nums) that sorts the list in place (smallest first) by swapping neighbours, and returns it. Don't use sorted or .sort().
Exercise
Write selection sort
Write selection_sort(nums). For each position i, find the index of the smallest value from i to the end, then swap it into position i. Return the list.
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 2
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.