Sorting CS Thinking Example 3

Follow the full solution, then compare it with the other examples linked below.

Example 3

medium
Sort [4, 1, 3] using insertion sort. Show each step.

Solution

  1. 1
    Step 1: Start with [4]. Insert 1: 1 < 4, so [1, 4]. Insert 3: 3 < 4 but 3 > 1, so [1, 3, 4].
  2. 2
    Step 2: Final sorted list: [1, 3, 4]. Two insertions were needed.

Answer

[1, 3, 4]
Insertion sort builds the sorted list one element at a time, inserting each new element into its correct position. It is efficient for small or nearly-sorted lists.

About Sorting

Rearranging items in a collection into a defined order, such as smallest to largest or alphabetical. Sorting is one of the most studied problems in computer science, with algorithms ranging from simple (bubble sort, O(n2)O(n^2)) to efficient (merge sort, O(nlogโกn)O(n \log n)).

Learn more about Sorting โ†’

More Sorting Examples