Implement insertion and merge sort
Implement insertion and merge sort
Insertion sort grows a sorted prefix by shifting larger elements right and inserting the next value. Merge sort divides input into halves, recursively sorts them and merges the sorted halves. Both can be stable: equal keys retain their original relative order.
package main
import ( "fmt")
func insertion(a []int) { for i := 1; i < len(a); i++ { v := a[i] j := i for j > 0 && a[j-1] > v { a[j] = a[j-1] j-- } a[j] = v }}func main() { a := []int{4, 1, 3, 1} insertion(a) fmt.Println(a)}The prefix before i is sorted. Strict > shifts only larger elements, preserving equal-key order. Worst-case O(n²), best-case O(n) for already sorted input, O(1) extra space. The function mutates the input.
Expected output:
[1 1 3 4]Merge two sorted halves
package main
import ( "fmt")
func mergeSort(a []int) []int { if len(a) < 2 { return append([]int(nil), a...) } m := len(a) / 2 l, r := mergeSort(a[:m]), mergeSort(a[m:]) out := make([]int, 0, len(a)) i, j := 0, 0 for i < len(l) && j < len(r) { if l[i] <= r[j] { out = append(out, l[i]) i++ } else { out = append(out, r[j]) j++ } } out = append(out, l[i:]...) return append(out, r[j:]...)}func main() { a := []int{5, 2, 4, 2} fmt.Println(mergeSort(a)) fmt.Println(a)}Choose from the left on ties for stability. Each level processes O(n) values over O(log n) levels, so time is O(n log n). This implementation returns a new slice and allocates O(n log n) elements in total, with O(n) peak live array storage in the algorithmic model plus recursion stack. Actual GC retention may differ. Prefer library sorting in production.
Expected output:
[2 2 4 5][5 2 4 2]Try it locally
Implement insertion sort for []int{9,-1,0,9}; check slices.IsSorted and print the slice. Also sort nil.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Algorithms 03: Implement insertion and merge sort
Check the lesson objective before moving on.
Why choose the left half on equal keys during merge?
What is insertion sort worst-case time?