-
Notifications
You must be signed in to change notification settings - Fork 0
/
insertion.go
55 lines (45 loc) · 943 Bytes
/
insertion.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package sorter
// InsertionSort sorts the given array according to insertion sort algorithm
// its complexity is O(n^2)
func InsertionSort(arr []int) []int {
var key int
var j int
for i := 1; i < len(arr); i++ {
key = arr[i]
j = i - 1
for j >= 0 && arr[j] > key {
arr[j+1] = arr[j]
j--
}
arr[j+1] = key
}
return arr
}
/////// Insertion Sort Recursively ////////
// RecursiveInsertionSort sorts the array recursively
func RecursiveInsertionSort(arr []int) []int {
lenArr := len(arr)
if lenArr < 2 {
return arr
}
newArr := arr[:lenArr-1]
r := RecursiveInsertionSort(newArr)
lastItem := arr[lenArr-1]
ins := Insert(r, lastItem)
return ins
}
// Insert inserts the array
func Insert(arr []int, key int) []int {
newArr := make([]int, len(arr)+1)
i := len(arr) - 1
for i >= 0 && arr[i] > key {
newArr[i+1] = arr[i]
i--
}
newArr[i+1] = key
for i >= 0 {
newArr[i] = arr[i]
i--
}
return newArr
}