Selection Sort

Algorithm:

Steps of the selection sort algorithm:

Estimation:

Code:

A selection sort implementation using functional programming might look like this:

def selectionSort[A: Ordering](list: List[A]): List[A] =
  @tailrec
  def loop(max: A, tail: List[A], zs: List[A], sorted: List[A]): List[A] =
    (tail, zs) match
      case (Nil, Nil)             => max :: sorted
      case (Nil, h :: t)          => loop(h, t, Nil, max :: sorted)
      case (h :: t, _) if max > h => loop(max, t, h :: zs, sorted)
      case (h :: t, _)            => loop(h, t, max :: zs, sorted)

  list match
    case Nil          => Nil
    case head :: tail => loop(head, tail, Nil, Nil)

selectionSort(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 four values (max, tail, zs, sorted) at each step of the recursive loop function:

Step max tail Operation zs sorted
1 3 1, 4, 2 3 > 1: keep 1 1 —
2 3 4, 2 3 < 4: new max = 4 3, 1 —
3 4 2 4 > 2: keep 2 2, 3, 1 —
4 4 — tail empty: max = 4 2, 3, 1 —
5 4 — (take 2 from zs) add 4 to sorted 3, 1 4
6 2 3, 1 2 < 3: new max = 3 2 4
7 3 1 3 > 1: keep 1 1, 2 4
8 3 — tail empty: max = 3 1, 2 4
9 3 — (take 1 from zs) add 3 to sorted - 3, 4
10 1 2 1 < 2: new max = 2 1 3, 4
11 2 — tail empty: max = 2 1 3, 4
12 2 — (take 1 from zs) add 2 to sorted — 2, 3, 4
13 1 — tail and zs are empty: done — 1, 2, 3, 4
flowchart TD
    S0["max = 3, tail = 1, 4, 2<br/>zs = —<br/>sorted = —"]

    subgraph p1[First selection — max is 4]
        P1["max = 3, tail = 4, 2<br/>zs = 1"]
        P2["max = 4, tail = 2<br/>zs = 3, 1"]
        P3["max = 4, tail = —<br/>zs = 2, 3, 1"]
        P4["max = 2, tail = 3, 1<br/>sorted = 4"]
    end

    subgraph p2[Second selection — max is 3]
        Q1["max = 3, tail = 1<br/>zs = 2<br/>sorted = 4"]
        Q2["max = 3, tail = —<br/>zs = 1, 2<br/>sorted = 4"]
        Q3["max = 1, tail = 2<br/>sorted = 3, 4"]
    end

    subgraph p3[Third selection — max is 2]
        R1["max = 2, tail = —<br/>zs = 1<br/>sorted = 3, 4"]
        R2["max = 1, tail = —<br/>sorted = 2, 3, 4"]
        R3["sorted = 1, 2, 3, 4"]
    end

    S0 --> P1 --> P2 --> P3 --> P4 --> Q1 --> Q2 --> Q3 --> R1 --> R2 --> R3

    style P4 fill:#d9ead3,stroke:#333
    style Q3 fill:#d9ead3,stroke:#333
    style R2 fill:#d9ead3,stroke:#333
    style R3 fill:#c9daf8,stroke:#333

Green highlights steps where the next maximum transitions into the head of the sorted part, and the final state is marked in blue.


Links: