Elementary sorts: bubble, selection, insertion
A sort that takes one line, sorted(), still compares two values and swaps them over and over inside. Step through the three simplest methods on 8 bars and count how many compares and swaps each one makes.
Short answer. All three repeat one move: compare two values, and swap them if they are in the wrong order. Bubble compares neighbors and pushes the big value to the right end. Selection picks the smallest of the rest and puts it at the front. Insertion takes values one at a time and slots each one into the sorted part on the left. For all three, doubling n makes the work about four times bigger (O(n²)), so they are not for big inputs. On small or almost sorted inputs, insertion sort is fast.
Pick a method and press "Next" to move one step at a time. A compare and a swap are separate steps. Blue bars joined by a two-headed arrow are the two being compared, with the result written above, like 7 < 8. Orange bars with two curved arrows crossing to each other's place are the two just swapped. Purple tags mark "smallest" (the smallest so far) in selection sort and "inserting" (the value being inserted) in insertion sort. Green bars with a bracket below are the part already in place. For insertion sort, the bracket means "sorted among the front part", so those bars can still shift before the end. The starting bars are 5, 2, 7, 1, 8, 3, 6, 4.
Try this. 1. Run bubble sort to the end: 25 compares and 13 swaps (40 steps). Everything is sorted after the fourth pass, but it only stops after a fifth pass with no swap at all. 2. Selection sort makes 28 compares and only 5 swaps. "swap" shows up at most once per pass. 3. Insertion sort makes 18 compares and 13 swaps. That is the same 13 swaps as bubble sort (section 4 explains why).
Definitions
The sections below explain with pictures and experiments. The textbook definitions are these. Call the values of the array a₁, a₂, …, aₙ. Sorting means putting them in a new order so that a₁ ≤ a₂ ≤ … ≤ aₙ.
- bubble sort
- A sort that repeats a pass from the left: compare two neighbors aⱼ, aⱼ₊₁ and swap them if aⱼ > aⱼ₊₁. After the k-th pass, the k largest values sit in their final places at the right end. It stops after a pass with no swap.
- selection sort
- A sort that, for each i = 1, 2, …, n − 1, finds the minimum of aᵢ, …, aₙ and swaps it with aᵢ. Finding the minimum needs a comparison with every remaining value, so the number of comparisons is the same for every input:
- insertion sort
- A sort that, for each i = 2, 3, …, n, puts aᵢ into the right place among the already sorted a₁, …, aᵢ₋₁, so that a₁, …, aᵢ are sorted. This page does it by swapping aᵢ with its left neighbor again and again while the neighbor is bigger.
- inversion
- A pair of positions (i, j) with i < j but aᵢ > aⱼ. Swapping two neighbors removes exactly one inversion, so in bubble sort and insertion sort, which swap only neighbors, the number of swaps equals the number of inversions I.
- stable sort
- A sort that keeps the relative order of elements with equal values. That is, if i < j and aᵢ = aⱼ, then after sorting the element that was aᵢ still comes before the element that was aⱼ.
- in-place sort
- A sort that only moves values around inside the input array and keeps a constant number of values (O(1)) outside it, no matter what n is.
1. The idea behind each method
Sorting means putting values in order, smallest first. The three methods on this page only do two things: compare (which of two values is bigger) and swap (exchange the values in two places). We measure the work by counting these two.
| Method | The idea in one line | What one pass does |
|---|---|---|
| Bubble sort | Compare neighbors and push the bigger one right. After one pass the biggest value has floated to the right end like a bubble | Swap when a[j] > a[j+1], from the left to the end. Stop after a pass with no swap |
| Selection sort | Scan the rest, pick (select) the smallest, and put it at the front of the rest | Find the smallest of the rest, then one swap with the front |
| Insertion sort | Like sorting cards in your hand: keep the left part sorted, take the next value and slot it into place | While the left neighbor of the taken value is bigger, swap them |
2. Work it out by hand
Follow insertion sort to the end on the starting bars 5, 2, 7, 1, 8, 3, 6, 4. The bar | marks the end of the sorted front part.
| Pass | Value taken | Left neighbors compared | After the pass | Compares | Swaps | Why it stopped |
|---|---|---|---|---|---|---|
| 1 | 2 | 5 | 2 5 | 7 1 8 3 6 4 | 1 | 1 | reached the front |
| 2 | 7 | 5 | 2 5 7 | 1 8 3 6 4 | 1 | 0 | 5 < 7 |
| 3 | 1 | 7, 5, 2 | 1 2 5 7 | 8 3 6 4 | 3 | 3 | reached the front |
| 4 | 8 | 7 | 1 2 5 7 8 | 3 6 4 | 1 | 0 | 7 < 8 |
| 5 | 3 | 8, 7, 5, 2 | 1 2 3 5 7 8 | 6 4 | 4 | 3 | 2 < 3 |
| 6 | 6 | 8, 7, 5 | 1 2 3 5 6 7 8 | 4 | 3 | 2 | 5 < 6 |
| 7 | 4 | 8, 7, 6, 5, 3 | 1 2 3 4 5 6 7 8 | 5 | 4 | 3 < 4 |
| Total | 18 | 13 |
In "Why it stopped", 5 < 7 means the left neighbor 5 is not bigger than the taken value 7. So there is no swap, and the pass stops.
When the left neighbor is not bigger (the 7 in passes 2 and 4, the 2 in pass 5), the pass stops there. The front part is already sorted, so there is no need to look further left. Reaching the front also ends the pass (passes 1 and 3).
On the same input, bubble sort changes the bars like this after each pass: 2 5 1 7 3 6 4 8, then 2 1 5 3 6 4 7 8, then 1 2 3 5 4 6 7 8, then 1 2 3 4 5 6 7 8, then a fifth pass with no swap, and it stops. That is 25 compares and 13 swaps in total. Selection sort makes 28 compares and 5 swaps.
3. The shape of the input matters
| Method | Compares | Swaps |
|---|
The input is the numbers 1 to n. "Shuffled" uses a fixed seed, so it is the same every time you open the page. "Almost sorted" starts sorted and then exchanges two values n ÷ 16 times (at least once). Each bar's length is its share of the worst case for compares, n(n − 1) ÷ 2.
Try this. 1. At the start (shuffled, n = 32): bubble makes 468 compares and 263 swaps, selection 496 and 31, insertion 290 and 263. 2. Switch to "Almost sorted": insertion makes 51 compares and 20 swaps. Bubble makes 196 compares, and selection still makes 496. 3. On "Already sorted", bubble and insertion make 31 compares (n − 1) and no swaps at all. Selection still makes 496 compares. 4. On "Reversed", bubble and insertion both make 496 compares and 496 swaps. Selection makes 496 compares and only 16 swaps. 5. On shuffled, raise n to 64: insertion makes 1015 compares. Doubling n took it from 290 to 1015, about 3.5 times more. Selection goes from 496 to 2016, exactly n(n − 1) ÷ 2.
How to read the way running time grows with n is on the time complexity page. n(n − 1) ÷ 2 becomes about four times bigger when n doubles, so we write it as O(n²).
4. Key properties
| Property | Bubble | Selection | Insertion |
|---|---|---|---|
| Compares | n − 1 to n(n − 1) ÷ 2 | always n(n − 1) ÷ 2 | n − 1 to n(n − 1) ÷ 2 |
| Swaps | the number of inversions | at most n − 1 | the number of inversions |
| On almost sorted input | a bit faster. A small value near the end moves left only one place per pass, which is slow | no change | fast |
| Stable (section 5) | yes | no | yes |
| In place (section 6) | yes | yes | yes |
An inversion is a pair where the value in front is bigger than the value behind it. 5, 2, 7, 1, 8, 3, 6, 4 has 13 of them (5 and 2, 5 and 1, and so on). Swapping two neighbors only changes the order of those two values, so it removes exactly one inversion. That is why bubble and insertion, which only swap neighbors, make exactly as many swaps as there are inversions. In each pass insertion sort compares once per swap, plus once more when it stops. So its compares are at least the number of inversions and at most the inversions plus n − 1. Almost sorted input has few inversions, so insertion sort finishes in close to n compares.
Selection sort has to scan all of the rest to know the smallest, whatever the input, so its compares never change. In return it swaps at most once per pass. This page does not swap, or count a swap, when the smallest is already in place (the algs4 book always swaps and counts n swaps).
5. Stable sorting: do equal values keep their order?
A sort is stable if values that are equal keep the order they had before sorting. With plain numbers you cannot see the difference. It matters when the value is one field of a record, like sorting orders by customer name. If orders are in date order and you sort them again by customer name, a stable sort keeps each customer's orders in date order. Python promises that sorted and list.sort are stable, so you can build a sort on several keys out of several sorts (see the Python docs in the sources).
- Bubble: stable. It swaps only when the left one is strictly bigger. Equal values are never swapped, so they never pass each other.
- Insertion: stable. The taken value moves left only while its left neighbor is strictly bigger. When it meets an equal value, it stops behind it.
- Selection: not stable. It swaps values that are far apart and can jump over an equal value. For example, in
[2ᵃ, 2ᵇ, 1]it swaps the smallest, 1, with 2ᵃ at the front and gets[1, 2ᵇ, 2ᵃ]. The two 2s have changed order.
If you write "swap when bigger or equal" instead of "swap when bigger", bubble and insertion also swap equal values and stop being stable. One comparison sign decides it.
6. In-place sorting
A sort is in place if it only moves values around inside the array it was given, and the extra memory is just a few values (the current position, where the smallest is). All three methods are in place. Some methods need extra memory the size of the whole array (merge sort). In Python, list.sort() changes the list in place, and sorted() builds and returns a new sorted list.
7. When to use which
| Method | Best case | Typical | Worst case | Extra memory | Use it when |
|---|---|---|---|---|---|
| Bubble sort | Already sorted: n − 1 compares. Double n, double the work (O(n)) | Double n, four times the work (O(n²)) | Reversed: n(n − 1) ÷ 2 compares and as many swaps. O(n²) | A few values (O(1)) | Learning. Insertion sort does the same job better |
| Selection sort | n(n − 1) ÷ 2 compares whatever the input. O(n²). At most n − 1 swaps | A few values (O(1)) | Swapping (writing) costs much more than comparing | ||
| Insertion sort | Already sorted: n − 1 compares. O(n) | Shuffled: about n²/4 compares and swaps. O(n²) | Reversed: n(n − 1) ÷ 2 compares and as many swaps. O(n²) | A few values (O(1)) | Small inputs, almost sorted inputs, adding values one at a time to a sorted list |
Built-in sortsorted, list.sort | About n log n even on big inputs. Details on the merge sort and quicksort page | Depends on the method | Almost every real case. Stable | ||
8. Code
def bubble_sort(a):
for end in range(len(a) - 1, 0, -1):
swapped = False
for j in range(end):
if a[j] > a[j + 1]: # compare neighbors, push the larger one back
a[j], a[j + 1] = a[j + 1], a[j]
swapped = True
if not swapped: # no swap in a pass: already sorted
break
return a
def selection_sort(a):
for i in range(len(a) - 1):
low = i
for j in range(i + 1, len(a)): # find the smallest of what is left
if a[j] < a[low]:
low = j
a[i], a[low] = a[low], a[i] # swaps across a gap (not stable)
return a
def insertion_sort(a):
for i in range(1, len(a)):
j = i
while j > 0 and a[j - 1] > a[j]: # swap only if the left one is bigger (stable)
a[j - 1], a[j] = a[j], a[j - 1]
j -= 1
return a
print(bubble_sort([5, 2, 7, 1, 8, 3, 6, 4])) # [1, 2, 3, 4, 5, 6, 7, 8]
print(selection_sort([5, 2, 7, 1, 8, 3, 6, 4])) # [1, 2, 3, 4, 5, 6, 7, 8]
print(insertion_sort([5, 2, 7, 1, 8, 3, 6, 4])) # [1, 2, 3, 4, 5, 6, 7, 8]
print(sorted([5, 2, 7, 1, 8, 3, 6, 4])) # what you use at work
Where it is used
- Small inputs. With few values even O(n²) finishes quickly, and the code is short and hard to get wrong.
- Almost sorted data. When a few values are added to a list that is already sorted, insertion sort finishes in close to n compares.
- When writes are expensive. If moving values costs much more than comparing them, selection sort makes the fewest swaps.
- A first step in learning sorting. Counting compares and swaps, stable sorting and in-place sorting all come back in merge sort and quicksort and in heaps.
Common questions
Do people write these three sorts by hand at work?
Almost never. You usually call the language's built-in sort (sorted and list.sort in Python). These three are worth learning because they are the smallest examples of counting compares and swaps, and of ideas like stable and in-place sorting. Fast ways to sort big inputs are on the merge sort and quicksort page.
How are bubble sort and insertion sort different?
Both only swap neighbors, so both make the same number of swaps: the number of inversions. The difference is the number of compares. In this page's experiment (n from 8 to 64, four input shapes) bubble sort never made fewer compares than insertion sort, and on almost sorted input the gap was large (196 against 51 at n = 32).
When does a stable sort matter?
When you sort by more than one key. Sort by the second key first, then sort again by the first key. With a stable sort, items that tie on the first key keep the order of the second key. Python promises that sorted and list.sort are stable, so this trick works there.
Words
| Plain words used here | Textbook term |
|---|---|
| compare | compare |
| swap | exchange, swap |
| one round over the array | pass |
| compare neighbors, push the big one right | bubble sort |
| pick the smallest, put it in front | selection sort |
| slot into the sorted part | insertion sort |
| a pair in the wrong order | inversion |
| almost sorted input | partially sorted array |
| equal values keep their order | stable sort |
| sorts inside the given array | in-place sort |
| double n, four times the work | O(n²), quadratic time |
Sources
- Robert Sedgewick, Kevin Wayne, Algorithms, 4th ed., 2.1 Elementary Sorts. Counting compares and exchanges, in-place sorting, compares and exchanges of selection and insertion sort, inversions and partially sorted arrays.
- Python docs, Sorting Techniques.
sortedandlist.sort, the promise that sorts are stable, and building a sort on several keys out of several sorts.