diff --git a/algorithms/isertion.go b/algorithms/isertion.go new file mode 100644 index 0000000..4cd9a2a --- /dev/null +++ b/algorithms/isertion.go @@ -0,0 +1,19 @@ +package algorithms + +func InsertionSort(arr []int) []int { + n := len(arr) + result := make([]int, n) + copy(result, arr) + + for i := 0; i < n; i++ { + for j, element := i-1, result[i]; j >= 0; j-- { + if element < result[j] { + result[j], result[j+1] = result[j+1], result[j] + } else { + result[j+1] = element + break + } + } + } + return result +} diff --git a/algorithms_test/insertion_test.go b/algorithms_test/insertion_test.go new file mode 100644 index 0000000..0c9761c --- /dev/null +++ b/algorithms_test/insertion_test.go @@ -0,0 +1,33 @@ +package algorithms_test + +import ( + "github.com/dimitrijjedich/go-algorithms/algorithms" + "reflect" + "testing" +) + +func TestInsertionSort(t *testing.T) { + testCases := []struct { + name string + input []int + expected []int + }{ + {"already sorted", []int{1, 2, 3, 4, 5}, []int{1, 2, 3, 4, 5}}, + {"reverse sorted", []int{5, 4, 3, 2, 1}, []int{1, 2, 3, 4, 5}}, + {"unsorted array", []int{5, 3, 8, 6, 2}, []int{2, 3, 5, 6, 8}}, + {"non consecutive array", []int{9, 3, 5, 1, 7}, []int{1, 3, 5, 7, 9}}, + {"empty array", []int{}, []int{}}, + {"single element", []int{42}, []int{42}}, + {"duplicates", []int{3, 1, 2, 3, 1}, []int{1, 1, 2, 3, 3}}, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + result := algorithms.InsertionSort(testCase.input) + + if !reflect.DeepEqual(result, testCase.expected) { + t.Errorf("Failed %s: expected %v, got %v", testCase.name, testCase.expected, result) + } + }) + } +}