-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsort.go
91 lines (84 loc) · 1.93 KB
/
sort.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
91
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"time"
)
// BUBBLE SORT
func BubbleSort(array []int) []int {
for i := 0; i < len(array); i++ {
for j := 0; j < len(array)-i-1; j++ {
if array[j] > array[j+1] {
array[j], array[j+1] = array[j+1], array[j]
}
}
}
return array
}
// MERGE SORT
func merge(left []int, right []int) []int {
final := []int{}
i := 0
j := 0
for i < len(left) && j < len(right) {
if left[i] < right[j] {
final = append(final, left[i])
i++
} else {
final = append(final, right[j])
j++
}
}
for ; i < len(left); i++ {
final = append(final, left[i])
}
for ; j < len(right); j++ {
final = append(final, right[j])
}
return final
}
func mergeSort(array []int) []int {
if len(array) < 2 {
return array
}
left := mergeSort(array[:len(array)/2])
right := mergeSort(array[len(array)/2:])
return merge(left, right)
}
func saveResults(method string, array []int) {
var filePath string = "./outputs/go" + method + ".json"
file, _ := json.MarshalIndent(array, "", " ") //this parse the array into a writable object
err := ioutil.WriteFile(filePath, file, 0644)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Sorted array by method = %s saved here %s !", method, filePath)
fmt.Println()
}
func main() {
data, err := ioutil.ReadFile("./inputs/randomNumbersArray.json")
if err != nil {
log.Fatal(err)
}
var numbers []int
var numbers2 []int
json.Unmarshal(data, &numbers)
json.Unmarshal(data, &numbers2)
// BUBBLE SORT
fmt.Println("Bubble Sort Started!")
bubbleStart := time.Now()
bubbleResult := BubbleSort(numbers)
fmt.Printf("BubbleSort: %s", time.Since(bubbleStart))
fmt.Println()
// MERGE SORT
fmt.Println("Merge Sort Started!")
mergeStart := time.Now()
mergeResult := mergeSort(numbers2)
fmt.Printf("MergeSort: %s", time.Since(mergeStart))
fmt.Println()
// Save sort results
saveResults("BubbleSort", bubbleResult)
saveResults("MergeSort", mergeResult)
}