Skip to content

Commit 423457d

Browse files
committed
feat: add insertion sort
1 parent da115c3 commit 423457d

File tree

3 files changed

+59
-1
lines changed

3 files changed

+59
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1196,7 +1196,7 @@ list.sort(Comparator.comparingInt(String::length));
11961196
| **Worst** | $O(n log n)$ | |
11971197
| **Average** | $O(n log n)$ | |
11981198

1199-
- Insertion sort, CLRS#2.1: [cpp](/cpp-algorithm/src/sort/sort.h), [java](/java-algorithm/src/main/java/com/example/algorithm/sort/InsertionSort.java) | Insertion sort is a comparison-based sorting algorithm that builds the final sorted array one element at a time. One of the fastest algorithms for sorting very small arrays (around 10 elements).<br>($\textit{n}$ is the number of elements)
1199+
- Insertion sort, CLRS#2.1: [cpp](/cpp-algorithm/src/sort/sort.h), [golang](go-algorithm/pkg/sort/insertion_sort.go), [java](/java-algorithm/src/main/java/com/example/algorithm/sort/InsertionSort.java) | Insertion sort is a comparison-based sorting algorithm that builds the final sorted array one element at a time. One of the fastest algorithms for sorting very small arrays (around 10 elements).<br>($\textit{n}$ is the number of elements)
12001200

12011201
| **Case** | **Time complexity** | **Remarks** |
12021202
| ----------- | :-----------------: | ------------------------------------------------------------------------------- |
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package sort
2+
3+
import (
4+
"golang.org/x/exp/constraints"
5+
)
6+
7+
func insertionSort[T constraints.Integer](arr []T) {
8+
for i := 0; i < len(arr); i++ {
9+
key := arr[i]
10+
j := i - 1
11+
for j >= 0 && arr[j] > key {
12+
arr[j+1] = arr[j]
13+
j--
14+
}
15+
arr[j+1] = key
16+
}
17+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package sort
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
"golang.org/x/exp/constraints"
8+
)
9+
10+
func Test_insertionSort(t *testing.T) {
11+
type args[T constraints.Integer] struct {
12+
arr []T
13+
}
14+
type testCase[T constraints.Integer] struct {
15+
name string
16+
args args[T]
17+
want []T
18+
}
19+
tests := []testCase[int]{
20+
{
21+
name: "Integer Case",
22+
args: args[int]{
23+
arr: []int{31, 64, 49, 85, 71, 26, 6, 19},
24+
},
25+
want: []int{6, 19, 26, 31, 49, 64, 71, 85},
26+
},
27+
{
28+
name: "Empty array input",
29+
args: args[int]{},
30+
want: nil,
31+
},
32+
}
33+
34+
for _, tt := range tests {
35+
t.Run(tt.name, func(t *testing.T) {
36+
insertionSort(tt.args.arr)
37+
38+
assert.Equalf(t, tt.want, tt.args.arr, "insertionSort() got = %v, want %v", tt.args.arr, tt.want)
39+
})
40+
}
41+
}

0 commit comments

Comments
 (0)