-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmergeSort.go
50 lines (38 loc) · 1.04 KB
/
mergeSort.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
package mergeSort
func Sort(arr []int) []int {
if len(arr) <= 1 {
return arr
}
midIndex := len(arr) / 2
leftArray := Sort(arr[:midIndex])
rightArray := Sort(arr[midIndex:])
return merge(leftArray, rightArray)
}
func merge(leftPile, rightPile []int) []int {
leftIndex := 0
rightIndex := 0
var orderedPile []int
for leftIndex < len(leftPile) && rightIndex < len(rightPile) {
if leftPile[leftIndex] < rightPile[rightIndex] {
orderedPile = append(orderedPile, leftPile[leftIndex])
leftIndex++
} else if leftPile[leftIndex] > rightPile[rightIndex] {
orderedPile = append(orderedPile, rightPile[rightIndex])
rightIndex++
} else {
orderedPile = append(orderedPile, leftPile[leftIndex])
leftIndex++
orderedPile = append(orderedPile, rightPile[rightIndex])
rightIndex++
}
}
for leftIndex < len(leftPile) {
orderedPile = append(orderedPile, leftPile[leftIndex])
leftIndex++
}
for rightIndex < len(rightPile) {
orderedPile = append(orderedPile, rightPile[rightIndex])
rightIndex++
}
return orderedPile
}