Insertion Sort

Algorithm:

Initially, the sorted sequence is empty. At each step, the insertion sort algorithm selects one of the input elements and inserts it into the correct position in the already sorted sequence until the input set is exhausted. At any point in time, the elements in the sorted sequence satisfy the output requirements of the algorithm.

Estimation:

Code:

An insertion sort implementation using functional programming might look like this:

def insertionSort[A: Ordering](list: List[A]): List[A] =
  @tailrec
  def sort(as: List[A], bs: List[A]): List[A] = as match
    case Nil    => bs
    case h :: t => sort(t, insert(h, bs))

  def insert(h: A, bs: List[A]): List[A] = bs match
    case hb :: tb if h > hb => hb :: insert(h, tb)
    case _                  => h :: bs

  sort(list, Nil)

insertionSort(List(3, 1, 4, 2))
// List(1, 2, 3, 4)

Visualization:

Let's see how the algorithm works on the example of the list 3, 1, 4, 2. Below is the state of the two lists (as, bs) at each step, where insert places the next element h at the correct position in the sorted part bs:

Step h Insert into bs bs after as
1 3 into empty list 3 1, 4, 2
2 1 1 < 3, insert at head 1, 3 4, 2
3 4 4 > 1, 3, insert at end 1, 3, 4 2
4 2 2 > 1, 2 < 3, insert between 1, 2, 3, 4 —
5 — as is empty: done 1, 2, 3, 4 —
flowchart TD
    S0["as = 3, 1, 4, 2<br/>bs = —"]

    subgraph p1[Insert 3]
        P1["h = 3, bs = —<br/>insert into empty list"]
        P2["as = 1, 4, 2<br/>bs = 3"]
    end

    subgraph p2[Insert 1]
        Q1["h = 1, bs = 3<br/>1 < 3, insert at head"]
        Q2["as = 4, 2<br/>bs = 1, 3"]
    end

    subgraph p3[Insert 4]
        R1["h = 4, bs = 1, 3<br/>4 > 1, 3, insert at end"]
        R2["as = 2<br/>bs = 1, 3, 4"]
    end

    subgraph p4[Insert 2]
        T1["h = 2, bs = 1, 3, 4<br/>2 > 1, 2 < 3, insert between"]
        T2["as = —<br/>bs = 1, 2, 3, 4"]
    end

    S0 --> P1 --> P2 --> Q1 --> Q2 --> R1 --> R2 --> T1 --> T2

    style P2 fill:#d9ead3,stroke:#333
    style Q2 fill:#d9ead3,stroke:#333
    style R2 fill:#d9ead3,stroke:#333
    style T2 fill:#c9daf8,stroke:#333

Green highlights states where the sorted part bs is extended with a new element, and the final state is marked in blue.


Links: