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 Go DSA implementation can be compared directly with the other languages.
Basic Implementation
basic.go
package main
import "fmt"
func main() {
arr := []int{5, 1, 4, 2, 8}
for i := 1; i < len(arr); i++ {
key := arr[i]
j := i - 1
for j >= 0 && arr[j] > key {
arr[j+1] = arr[j]
j--
}
arr[j+1] = key
}
fmt.Println(arr)
}
Complexity
- Time: O(n^2) worst and average, O(n) best
- Space: O(1)
- Stable: yes
Implementation notes
- Go builds
arrwith the slice literal[]int{5, 1, 4, 2, 8}; the slice header points at one backing array that is mutated in place. - The outer loop is
for i := 1; i < len(arr); i++. Each pass copiesarr[i]into localkeybefore shifts overwrite that slot. j := i - 1is anint, so the loop can testj >= 0before readingarr[j]; Go still performs normal bounds checks on each indexed access.- Shifts write
arr[j+1] = arr[j], thenarr[j+1] = keyplaces the saved value after the loop opens the slot. - 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]; the final8pass does not move. fmt.Println(arr)uses Go's default slice formatting and prints[1 2 4 5 8], without commas.
sorted prefix
Positions before the scan index are already sorted.
shifting
Larger values move one slot right to make room for the key.