Insertion sort

Published

2023-08-05

Insertion sort is another sorting algorithm. Insertion sort tends to be faster than bubble sort or selection sort. Here’s how it works.

  1. Start by treating the first element as sorted.
  2. Take the first unsorted element and shift sorted elements to the right (as needed) to make an appropriate space for the element we wish to sort.
  3. Insert the element into the appropriate place,
  4. Repeat for each unsorted element in turn.

The important thing to notice here is that unlike selection sort or bubble sort, insertion sort ignores all unsorted values but one in each iteration.

Here we implement insertion sort in C++ and we perform a time comparison between bubble sort, selection sort and insertion sort, when operating on shuffled vectors of 1000 distinct elements.

We ran 1000 trials, sorting randomized vectors of 1000 distinct elements, using bubble sort, selection sort, and insertion sort. Here are the results of our experiment.

time comparison

Additional resources:

Comprehension check:

  1. True or false?Insertion sort is stable.
  2. True or false? Insertion sort can process data on-line (i.e., data can be added to the vector while the algorithm is running).
  3. Insertion sort has time complexity of ________ and space complexity of _____________.
  4. True or false? On each iteration, insertion sort performs a comparison of the current unsorted element with each of the other unsorted elements.
  5. Given the vector 5, 7 , 6, 3, 0, 2, with the two leftmost elements already sorted, after the next iteration the vector will be 5, 6, 7, 3, 0, 2.

Answers: ǝnɹʇ / ǝslɐɟ / (Ɩ)O / (ᄅ^u)O / ǝnɹʇ / ǝnɹʇ

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

All materials copyright © 2020–2023, The University of Vermont. All rights reserved.