-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultisort.go
More file actions
96 lines (78 loc) · 1.88 KB
/
multisort.go
File metadata and controls
96 lines (78 loc) · 1.88 KB
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
92
93
94
95
96
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
"strings"
"sync"
)
var wg sync.WaitGroup
func sortSlice(slc []int, tname string) {
fmt.Println("thread-", tname, " will sort", slc)
sort.Ints(slc)
fmt.Println("subresult: of thread-", tname, "->", slc)
defer wg.Done()
}
func convertLineToArray(line string) []int {
s := strings.Split(line, " ")
var numbers []int
for _, v := range s {
num, err := strconv.Atoi(v)
if err != nil {
panic(err)
}
numbers = append(numbers, num)
}
return numbers
}
func findMin(arr []int, indexes []int) (int, int) {
minIndex := 0
minValue := arr[indexes[minIndex]]
for index, i := range indexes {
if arr[i] < minValue {
minIndex = index
minValue = arr[i]
}
}
return minValue, minIndex
}
func removeIndex(slice []int, s int) []int {
return append(slice[:s], slice[s+1:]...)
}
func main() {
fmt.Println("Please enter the number you want to sort, separated by space")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
numbers := convertLineToArray(scanner.Text())
numberOfRoutines := 4
sliceSize := len(numbers) / numberOfRoutines
sliceStarts := make([]int, numberOfRoutines+1)
for i := 0; i < numberOfRoutines; i++ {
sliceStarts[i] = i * sliceSize
}
sliceStarts[numberOfRoutines] = len(numbers)
for i := 0; i < numberOfRoutines; i++ {
wg.Add(1)
go sortSlice(numbers[sliceStarts[i]:sliceStarts[i+1]], strconv.Itoa(i+1))
}
wg.Wait()
//merge
result := make([]int, 0)
sliceIndexes := make([]int, numberOfRoutines)
copy(sliceIndexes, sliceStarts[:len(sliceStarts)-1])
for {
if len(result) >= len(numbers) {
break
}
minValue, minIndex := findMin(numbers, sliceIndexes)
result = append(result, minValue)
if sliceIndexes[minIndex]+1 < sliceStarts[minIndex+1] {
sliceIndexes[minIndex]++
} else {
sliceIndexes = removeIndex(sliceIndexes, minIndex)
}
}
fmt.Println("The result is", result)
}