Sorting
Insertion Sort
Build the sorted prefix one item at a time, shifting larger values right until the current key can be inserted.
Algorithm
The checked-in replay follows the same small input and final output across all 21 DSA books, so this Scala DSA implementation can be compared directly with the other languages.
Basic Implementation
basic.scala
object Main {
def main(args: Array[String]): Unit = {
val arr = Array(5, 1, 4, 2, 8)
for (i <- 1 until arr.length) {
val key = arr(i)
var j = i - 1
while (j >= 0 && arr(j) > key) {
arr(j + 1) = arr(j)
j = j - 1
}
arr(j + 1) = key
}
println(arr.mkString("[", ", ", "]"))
}
}
Complexity
- Time: O(n^2) worst and average, O(n) best
- Space: O(1)
- Stable: yes
Implementation notes
val arr = Array(5, 1, 4, 2, 8)fixes the ScalaArray[Int]reference, but the array slots are still mutable.- The outer loop
for (i <- 1 until arr.length)uses an exclusive range, so index0starts as the sorted prefix and indices1through4are inserted. val key = arr(i)copies the currentIntbefore shifts overwrite slots;var j = i - 1tracks the scan position moving left.- The while condition
j >= 0 && arr(j) > keychecks the lower bound before readingarr(j), then compares ScalaIntvalues directly. - Shifting is assignment,
arr(j + 1) = arr(j), followed byj = j - 1; the final write-back isarr(j + 1) = key. - The trace shows
[5, 1, 4, 2, 8], then inserting1gives[1, 5, 4, 2, 8], shifting5for key4gives[1, 4, 5, 2, 8], and shifting5and4for key2gives[1, 2, 4, 5, 8]. println(arr.mkString("[", ", ", "]"))prints the final array as[1, 2, 4, 5, 8].
sorted prefix
Positions before the scan index are already sorted.
shifting
Larger values move one slot right to make room for the key.