forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_sort_sequential.go
90 lines (60 loc) · 1.63 KB
/
merge_sort_sequential.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"fmt"
"time"
)
// merge(): a simple function which merge the two slices into one slice
func merge(left []int, right []int) []int {
result := make([]int, len(left)+len(right))
leftArrayIndex, rightArrayIndex := 0, 0
for resultArrayIndex := 0; resultArrayIndex < len(result); resultArrayIndex++ {
if leftArrayIndex >= len(left) {
result[resultArrayIndex] = right[rightArrayIndex]
rightArrayIndex++
continue
} else if rightArrayIndex >= len(right) {
result[resultArrayIndex] = left[leftArrayIndex]
leftArrayIndex++
continue
}
if left[leftArrayIndex] < right[rightArrayIndex] {
result[resultArrayIndex] = left[leftArrayIndex]
leftArrayIndex++
} else {
result[resultArrayIndex] = right[rightArrayIndex]
rightArrayIndex++
}
}
return result
}
func mergeSort(arr []int) []int {
length := len(arr)
if length < 2 {
return arr
}
left := arr[0 : length/2]
right := arr[length/2:]
// making recursive call with mergeSort() function on both halves of slice
left = mergeSort(left)
right = mergeSort(right)
return merge(left, right)
}
func main() {
arr := []int{3, 5, 1, 6, 1, 7, 2, 4, 5, 1}
start := time.Now() // adding timestamp when excecution of mergesort start
arr = mergeSort(arr)
end := time.Now() // adding timestamp when excecution of mergesort finish
fmt.Println("sorted array is")
fmt.Println(arr)
fmt.Println("time taken by algorithm is")
fmt.Println(end.Sub(start))
}
/*
input/output sample
sorted array is
[1 1 1 2 3 4 5 5 6 7]
time taken by algorithm is
2.535µs
Time Complexity: O(nLog(n)) in worst case
Space Complexity: O(n) in worst case
*/