Simple Sorts

How insertion, selection and bubble sort work, why they take O(n²) time, when insertion sort is still the right choice, and what interviewers ask.

14 minLesson 1 of 7
On this page
  1. How the three algorithms work
  2. Insertion sort, step by step
  3. Selection sort
  4. Bubble sort
  5. Time and space
  6. Stability
  7. When not to use these sorts
  8. Pitfalls
  9. In the interview
  10. What to practise next

Insertion sort, selection sort and bubble sort are the three simple sorting algorithms. Each one sorts an array by repeatedly comparing and moving items, in a few lines of code and with no extra memory. They take O(n²) time, so they are too slow for large inputs, but insertion sort is the fastest choice for very small or nearly sorted arrays. You need to know all three because interviewers use them to check that you can analyse a loop and reason about stability.

Without a basic sorting algorithm you would fall back on the library sort, which is the right choice in real code but hides the questions interviewers care about: how many comparisons and moves an algorithm makes, and what it does to items that compare as equal.

How the three algorithms work

All three keep a sorted part at the front of the array and an unsorted part after it. Each round moves one more item into the sorted part. They differ in which item they choose and how they put it in place.

  • Insertion sort takes the next item in the unsorted part and slides it left until it is in the right place among the sorted items.
  • Selection sort scans the whole unsorted part for the smallest item and swaps it into the first unsorted position.
  • Bubble sort walks along the array and swaps neighbours that are out of order, which carries the largest remaining item to the end on each pass.
3 7 9 4 1 sorted part unsorted part 4 slides past 9 and 7
Insertion sort partway through: 3, 7 and 9 are sorted, and 4 is about to slide left past 9 and 7 to sit after 3.

Insertion sort, step by step

Insertion sort starts with the first item as a sorted part of length one. For each following item, it copies the item into a variable called key, shifts every larger sorted item one slot to the right, and writes key into the gap that opens up. The copy matters because the first shift overwrites the slot that the item came from.

Insertion sort on [7, 3, 9, 4, 1]Use the arrows or ← → keys
for i from 1 to n - 1:  key = a[i]  j = i - 1  while j >= 0 and a[j] > key:    a[j + 1] = a[j]    j = j - 1  a[j + 1] = key
  1. a
    07
    13i
    29
    34
    41

    1The first item, 7, is already a sorted part of length one, so the loop starts at i = 1.

  2. a
    07j
    13i
    29
    34
    41
    key
    3

    2The algorithm copies 3 into key and compares it with 7.

  3. a
    j
    07
    17i
    29
    34
    41
    key
    3

    37 is larger than the key, so it shifts one slot to the right. The array now shows 7 twice, but 3 is safe in key.

  4. a
    03
    17i
    29
    34
    41
    key
    3

    4j has moved past the front of the array, so 3 is written into slot 0. The sorted part is now 3, 7.

  5. a
    03
    17j
    29i
    34
    41
    key
    9

    5The key is 9. The item to its left, 7, is not larger, so 9 stays where it is after one comparison and no shifts.

  6. a
    03
    17
    29j
    39i
    41
    key
    4

    6The key is 4. The item 9 is larger, so it shifts one slot to the right.

  7. a
    03
    17j
    27
    39i
    41
    key
    4

    7The item 7 is also larger than 4, so it shifts to the right as well.

  8. a
    03j
    17
    27
    39i
    41
    key
    4

    8The item 3 is not larger than 4, so the loop stops. The gap is at slot 1, just to the right of j.

  9. a
    03
    14
    27
    39
    41i
    key
    4

    9The algorithm writes 4 into slot 1. The first four items are sorted.

  10. a
    03
    14
    27
    39j
    49i
    key
    1

    10The key is 1. The item 9 is larger, so it shifts one slot to the right.

  11. a
    03
    14
    27j
    37
    49i
    key
    1

    11The item 7 is larger than 1, so it shifts to the right.

  12. a
    03
    14j
    24
    37
    49i
    key
    1

    12The item 4 is larger than 1, so it shifts to the right.

  13. a
    j
    03
    13
    24
    37
    49i
    key
    1

    13The item 3 is larger than 1, so it shifts to the right, and j moves past the front of the array.

  14. a
    01
    13
    24
    37
    49
    key
    1

    14The algorithm writes 1 into slot 0, and the whole array is sorted.

  15. a
    01
    13
    24
    37
    49
    shifts
    7
    comparisons
    9

    15The run used 7 shifts and 9 comparisons. The 7 shifts equal the 7 pairs that started in the wrong order, such as (7, 3) and (9, 4).

1 / 15

The last step shows the fact that explains insertion sort's running time: each shift removes exactly one pair of items that are in the wrong order. An already sorted array has no such pairs, so insertion sort makes one comparison per item and finishes in O(n). An array that is almost sorted has only a few such pairs and is nearly as fast.

Insertion sort
function insertionSort(a) {
  for (let i = 1; i < a.length; i++) {
    const key = a[i];
    let j = i - 1;
    // shift larger items one slot right to open a gap
    while (j >= 0 && a[j] > key) {
      a[j + 1] = a[j];
      j--;
    }
    a[j + 1] = key; // the gap is just right of j
  }
  return a;
}
 
insertionSort([7, 3, 9, 4, 1]); // [1, 3, 4, 7, 9]
def insertion_sort(a):
    for i in range(1, len(a)):
        key = a[i]
        j = i - 1
        # shift larger items one slot right to open a gap
        while j >= 0 and a[j] > key:
            a[j + 1] = a[j]
            j -= 1
        a[j + 1] = key  # the gap is just right of j
    return a
 
insertion_sort([7, 3, 9, 4, 1])  # [1, 3, 4, 7, 9]

Selection sort

Selection sort scans the unsorted part to find the position of the smallest item and swaps that item into the first unsorted position. After round one the smallest item is in slot 0, after round two the second smallest is in slot 1, and so on. Because each round places one item in its final position with a single swap, selection sort makes at most n − 1 swaps. That is useful only when writing to the array is much more expensive than reading it, for example when each write wears out flash memory.

The scan always runs to the end of the array, whatever the input looks like, so selection sort makes the same n(n − 1) / 2 comparisons on sorted input as on shuffled input. It is the only one of the three that gets no benefit from an input that is already sorted.

Bubble sort

Bubble sort makes repeated passes over the array and swaps every neighbouring pair that is out of order. After the first pass the largest item has been carried to the last slot, after the second pass the second largest is in the second to last slot, and so on, so each pass can stop one slot earlier than the previous one. If a whole pass makes no swaps, the array is sorted and the algorithm can stop.

With that early stop, bubble sort takes O(n) time on sorted input. It still makes as many swaps as insertion sort makes shifts, one for each pair in the wrong order, and a swap writes two slots where a shift writes one. Each pass also compares pairs that are already in order, where insertion sort stops as soon as an item fits. In practice bubble sort is slower than insertion sort on the same data, and the only reason to learn it is that interviewers still mention it.

Selection sort and bubble sort
function selectionSort(a) {
  for (let i = 0; i < a.length - 1; i++) {
    let min = i;
    for (let j = i + 1; j < a.length; j++) {
      if (a[j] < a[min]) min = j;
    }
    [a[i], a[min]] = [a[min], a[i]]; // one swap per round
  }
  return a;
}
 
function bubbleSort(a) {
  for (let end = a.length - 1; end > 0; end--) {
    let swapped = false;
    for (let j = 0; j < end; j++) {
      if (a[j] > a[j + 1]) {
        [a[j], a[j + 1]] = [a[j + 1], a[j]];
        swapped = true;
      }
    }
    if (!swapped) break; // no swaps: already sorted
  }
  return a;
}
def selection_sort(a):
    for i in range(len(a) - 1):
        smallest = i
        for j in range(i + 1, len(a)):
            if a[j] < a[smallest]:
                smallest = j
        a[i], a[smallest] = a[smallest], a[i]  # one swap per round
    return a
 
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]:
                a[j], a[j + 1] = a[j + 1], a[j]
                swapped = True
        if not swapped:  # no swaps: already sorted
            break
    return a

Time and space

In the worst case, a reversed array, insertion sort shifts the second item 1 slot, the third item 2 slots, and so on up to n − 1 slots for the last item. The total is 1 + 2 + … + (n − 1) = n(n − 1) / 2, which grows as O(n²). Selection sort always makes that many comparisons, and bubble sort makes that many in the worst case. All three sort inside the array they are given and use O(1) extra space, which is called sorting in place.

ApproachTimeSpaceWhy
Insertion sortO(n²)O(1)O(n) on sorted or nearly sorted input. Stable.
Selection sortO(n²)O(1)Always n(n − 1)/2 comparisons, but at most n − 1 swaps. Not stable.
Bubble sortO(n²)O(1)O(n) on sorted input with the early stop. Stable.

Stability

A sort is stable if items with equal keys stay in the order they had before the sort. This matters when you sort records by one field after sorting by another. Suppose a list is in alphabetical order, Ann 82, Ben 75, Cal 82, Dee 75, and you sort it by score. A stable sort gives Ben 75, Dee 75, Ann 82, Cal 82, so the names are still alphabetical within each score.

Insertion sort is stable because it shifts an item past only the items that are strictly larger, so an equal item is never jumped over. Bubble sort is stable for the same reason, since it swaps only when the left item is strictly larger. Selection sort is not stable, because its swap moves an item a long way and can jump it over an equal item. On the list above, round one swaps Ben to the front, giving Ben, Ann, Cal, Dee. Round two swaps Dee with Ann, giving Ben, Dee, Cal, Ann, and now Cal 82 comes before Ann 82, which reverses their original order.

When not to use these sorts

For arrays of more than a few dozen items that are not nearly sorted, O(n²) is too slow. With 10,000 items the worst case is about 50 million steps, and with a million items it is about 500 billion. Use the language's built-in sort for real code, or merge sort or quicksort when the interviewer asks you to write an O(n log n) sort yourself.

Insertion sort is still used inside those faster sorts. Python's built-in sort and the sort in V8, the JavaScript engine used by Chrome and Node, both use Timsort. It finds stretches of the input that are already sorted, extends short ones with insertion sort, and merges them. Insertion sort works well there because it has very little overhead on small or nearly sorted pieces.

Pitfalls

In the interview

You will rarely be asked to code a simple sort for its own sake. More often a problem statement hints that one fits: the array is almost sorted, only a few items are out of place, the input is tiny, or the problem asks for the number of swaps or out-of-order pairs. You can also be asked to sort in place with O(1) extra space and no library call, or to explain why a sort must be stable. When the input is large and unordered, say that you would use the built-in sort and give its O(n log n) cost.

Questions to expect:

  • "What is the best case of insertion sort?" A sorted array, where each item needs one comparison and no shifts, so the time is O(n). It also does well on nearly sorted input, because the number of shifts equals the number of pairs that are out of order.
  • "Why is selection sort not stable, and can you make it stable?" Its swap moves an item across the array and can jump it over an equal item. You can make it stable by shifting the items between the two positions instead of swapping, but that adds O(n) writes per round and removes its one advantage of making few writes.
  • "Which sort makes the fewest writes?" Selection sort, with at most n − 1 swaps. Insertion sort and bubble sort both make one move for every pair that is in the wrong order, which is up to n(n − 1) / 2 in the worst case.
  • "Why is insertion sort used inside faster algorithms?" The O(n log n) algorithms have recursion and merging overhead that costs more than it saves on a handful of items. On small pieces, which are often nearly sorted already, insertion sort is faster in practice, so libraries switch to it below a small size.
  • "How many swaps does it take to sort an array?" If swaps may only exchange neighbours, the minimum equals the number of pairs in the wrong order, which is what bubble sort uses. If swaps may exchange any two items, the minimum is lower and depends on the cycles in the permutation, so check which kind the problem allows.
  • "Can you do better than O(n²) with comparisons?" Yes, merge sort, quicksort and heap sort take O(n log n). No comparison-based sort can beat O(n log n) in the worst case, and sorting without comparisons, as in counting sort, can reach O(n) when the keys are small integers.
Quick check

You run insertion sort on an array of 1,000 items that is already sorted. About how many comparisons does it make?

Orders are listed by time: (A, $5), (B, $3), (C, $5). You sort them by price with a stable sort. What is the result?

Which simple sort makes the fewest swaps on a reversed array of 6 items?

Why does selection sort stay O(n²) on an array that is already sorted?

What to practise next

Trace insertion sort by hand on [5, 1, 4, 2], where you should count 4 shifts. Then read Merge Sort, which reaches O(n log n) and stays stable by sorting each half and merging the results.