From f83219ecdf2e7f8bb3fdaae8d460b1ee4ef1350b Mon Sep 17 00:00:00 2001 From: dimitrijjedich Date: Mon, 25 Nov 2024 05:10:48 +0100 Subject: [PATCH 1/3] initial commit --- algorithms/isertion.go | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 algorithms/isertion.go diff --git a/algorithms/isertion.go b/algorithms/isertion.go new file mode 100644 index 0000000..2ac9a99 --- /dev/null +++ b/algorithms/isertion.go @@ -0,0 +1,5 @@ +package algorithms + +func InsertionSort(arr []int) []int { + return arr +} From 76cc43ac06106caf17bf8f4af2b64a87def6429f Mon Sep 17 00:00:00 2001 From: dimitrijjedich Date: Mon, 25 Nov 2024 07:37:37 +0100 Subject: [PATCH 2/3] add initial implementation --- algorithms/isertion.go | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/algorithms/isertion.go b/algorithms/isertion.go index 2ac9a99..4cd9a2a 100644 --- a/algorithms/isertion.go +++ b/algorithms/isertion.go @@ -1,5 +1,19 @@ package algorithms func InsertionSort(arr []int) []int { - return arr + 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 } From ecc5aa955e787301d577ad83128c05de5698cf5b Mon Sep 17 00:00:00 2001 From: dimitrijjedich Date: Mon, 25 Nov 2024 07:37:54 +0100 Subject: [PATCH 3/3] add tests for insertion sort algorithm --- algorithms_test/insertion_test.go | 33 +++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 algorithms_test/insertion_test.go 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) + } + }) + } +}