Lesson contents

Insertion sort

Build a sorted part from left to right. Take the next item, shift larger neighbours aside and put the item in the gap.

Simple example

Insert 1 before 3, then slide 3 aside again to insert 2. Print the sorted values.

Start3 1 2
Result1 2 3
Lesson.scala
object Lesson {
  def main(args: Array[String]): Unit = {
        var values = Array(3, 1, 2)
        var i = 1
        while (i < 3) {
            var key = values(i)
            var j = i - 1
            while ((j >= 0) && (values(j) > key)) {
                values(j + 1) = values(j)
                j -= 1
            }
            values(j + 1) = key
            i += 1
        }
        i = 0
        while (i < 3) {
            println(values(i))
            i += 1
        }
  }
}
Output
1
2
3
Advertisements

Everyday examples

Place a new ticket

A clerk keeps tickets 2, 5 and 8 in order. Where should ticket 6 go?

Start2 5 8 +6
Result2 5 6 8

Slide 8 right. The open spot after 5 is the insertion position.

Add a morning appointment

Your diary starts at 10 and 12. Add an appointment at 9.

Start10 12 +9
Result9 10 12

Both later appointments shift one position to make room.

Append a late payment

A sorted ledger ends with days 4 and 6. A payment for day 7 arrives. What shifts?

Start4 6 +7
Result4 6 7

The last existing day already precedes 7. Append it without shifting the other entries.

Cost and limits

Insertion sort works well on short or nearly sorted lists. Reverse order requires O(n²) moves and comparisons.