Algorithm and Data Structures - Insertion Sort

Learn Insertion Sort, which divides the array into sorted and unsorted parts and builds the sorted sequence one element at a time. O(n²) time complexity with a Go implementation.

Read in: ja
Algorithm and Data Structures - Insertion Sort

Overview

Referencing the Algorithm Encyclopedia, we learn about algorithms and data structures.

The implementation is also available on github - bmf-san/road-to-algorithm-master.

Insertion Sort

Time Complexity

Implementation

package main

import "fmt"

func insertionSort(n []int) []int {
	for i := 1; i < len(n); i++ {
		for j := 0; j < i; j++ {
			if n[i-j-1] > n[i-j] {
				n[i-j-1], n[i-j] = n[i-j], n[i-j-1]
			} else {
				break
			}
		}
	}

	return n
}

func main() {
	n := []int{2, 1, 5, 7, 9}
	fmt.Println(insertionSort(n))
}

References

Tags: Insertion Sort
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles