diff --git a/insertion_sort.go b/insertion_sort.go new file mode 100644 index 0000000..6d439ef --- /dev/null +++ b/insertion_sort.go @@ -0,0 +1,43 @@ +package algorithms + +// InsertionSort is an implementation of insertion sort algorithm. +// Wikipedia: https://en.wikipedia.org/wiki/Insertion_sort +// +// Insertion sort iterates, consuming one input element each repetition, and +// growing a sorted output list. Each iteration, insertion sort removes one +// element from the input data, finds the location it belongs within the sorted +// list, and inserts it there. It repeats until no input elements remain. +func InsertionSort(a []int) []int { + for i := 0; i < len(a); i++ { + for j := i; j > 0 && a[j] < a[j-1]; j-- { + a[j-1], a[j] = a[j], a[j-1] + } + } + + return a +} + +// InsertionSortOptimized is an optimized implementation of insertion sort +// algorithm. +func InsertionSortOptimized(a []int) []int { + // Moving the "sentinel" value to the first position + for i := len(a) - 1; i > 0; i-- { + if a[i] < a[i-1] { + a[i-1], a[i] = a[i], a[i-1] + } + } + if len(a) < 3 { + return a + } + + for i := 2; i < len(a); i++ { + val := a[i] + j := i + for ; val < a[j-1]; j-- { + a[j] = a[j-1] + } + a[j] = val + } + + return a +} diff --git a/insertion_sort_test.go b/insertion_sort_test.go new file mode 100644 index 0000000..43eb88d --- /dev/null +++ b/insertion_sort_test.go @@ -0,0 +1,65 @@ +package algorithms + +import ( + "testing" +) + +func TestInsertionSort(t *testing.T) { + testInsertionSort(t, InsertionSort, + []int{5, 3, 1, 4, 2}, + []int{1, 2, 3, 4, 5}, + ) +} + +func TestInsertionSortOptimized(t *testing.T) { + testInsertionSort(t, InsertionSortOptimized, + []int{5, 3, 1, 4, 2}, + []int{1, 2, 3, 4, 5}, + ) +} + +func TestInsertionSortOptimizedTwoItems(t *testing.T) { + testInsertionSort(t, InsertionSortOptimized, + []int{2, 1}, + []int{1, 2}, + ) +} + +func BenchmarkInsertionSort(b *testing.B) { + for i := 0; i < b.N; i++ { + InsertionSort(unsortedArray()) + } +} + +func BenchmarkInsertionSortOptimized(b *testing.B) { + for i := 0; i < b.N; i++ { + InsertionSortOptimized(unsortedArray()) + } +} + +func testInsertionSort(t *testing.T, sortFun func([]int) []int, a, exp []int) { + s := sortFun(a) + if len(s) != len(exp) { + t.Fatal("Array sizes don't match") + } + for i := 0; i < len(exp); i++ { + if s[i] != exp[i] { + t.Fatalf("Expected sorted array to equal %v, got %v", exp, s) + } + } +} + +func unsortedArray() []int { + return []int{ + 57, 64, 83, 25, 26, 10, 55, 22, 76, 61, + 28, 77, 56, 32, 63, 17, 91, 20, 58, 16, + 1, 51, 88, 82, 24, 70, 81, 35, 49, 39, + 89, 30, 46, 6, 41, 19, 43, 67, 53, 97, + 65, 37, 13, 23, 29, 69, 0, 73, 9, 59, + 96, 34, 66, 79, 27, 14, 40, 80, 98, 2, + 5, 45, 50, 4, 85, 18, 86, 7, 87, 31, + 95, 47, 68, 36, 15, 48, 8, 92, 11, 74, + 78, 52, 44, 42, 54, 84, 12, 21, 38, 99, + 72, 33, 71, 93, 60, 62, 90, 94, 3, 75, + } +}