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 Kotlin DSA implementation can be compared directly with the other languages.
Basic Implementation
basic.kt
fun main() {
val arr = intArrayOf(5, 1, 4, 2, 8)
for (i in 1 until arr.size) {
val key = arr[i]
var j = i - 1
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j]
j--
}
arr[j + 1] = key
}
println(arr.joinToString(prefix = "[", postfix = "]"))
}
Complexity
- Time: O(n^2) worst and average, O(n) best
- Space: O(1)
- Stable: yes
Implementation notes
- Kotlin stores the input in a primitive
IntArrayfromintArrayOf(5, 1, 4, 2, 8). Thearrbinding is aval, but the array slots are still mutated in place. - The outer loop uses
for (i in 1 until arr.size), so each pass reads a non-nullIntkey fromarr[i]without revisiting index0. keyis avalcopy of the current element, whilejis a mutablevarinitialized toi - 1and decremented during shifts.- The while guard
j >= 0 && arr[j] > keyshort-circuits beforearr[j]is read with a negative index, and uses strictIntcomparison for stability. - Shifts are explicit slot writes:
arr[j + 1] = arr[j], followed by the final placementarr[j + 1] = key; no new array is allocated for the sort. - The trace records
[5, 1, 4, 2, 8], then[1, 5, 4, 2, 8],[1, 4, 5, 2, 8], and[1, 2, 4, 5, 8]after inserting2. println(arr.joinToString(prefix = "[", postfix = "]"))formats the mutated 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.