You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
91 lines
1.6 KiB
Go
91 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
)
|
|
|
|
func Swap(sli []int, i int) {
|
|
sli[i], sli[i+1] = sli[i+1], sli[i]
|
|
}
|
|
|
|
func BubbleSort(sli []int, wg *sync.WaitGroup) {
|
|
fmt.Println(sli)
|
|
swapped := true
|
|
for limit := len(sli) - 1; limit > 0 && swapped == true; limit-- {
|
|
swapped = false
|
|
for i := 0; i < limit; i++ {
|
|
if sli[i] > sli[i+1] {
|
|
Swap(sli, i)
|
|
swapped = true
|
|
}
|
|
}
|
|
}
|
|
wg.Done()
|
|
}
|
|
|
|
func Merge(sli1, sli2 []int) []int {
|
|
sorted := make([]int, 0, len(sli1)+len(sli2))
|
|
i, j := 0, 0
|
|
for i < len(sli1) && j < len(sli2) {
|
|
if sli1[i] < sli2[j] {
|
|
sorted = append(sorted, sli1[i])
|
|
i++
|
|
} else {
|
|
sorted = append(sorted, sli2[j])
|
|
j++
|
|
}
|
|
}
|
|
if i < len(sli1) {
|
|
sorted = append(sorted, sli1[i:]...)
|
|
} else {
|
|
sorted = append(sorted, sli2[j:]...)
|
|
}
|
|
return sorted
|
|
}
|
|
|
|
func main() {
|
|
var seq []int
|
|
OuterLoop:
|
|
for seq == nil {
|
|
scanner := bufio.NewScanner(os.Stdin)
|
|
fmt.Println(
|
|
"Type in a sequence of space-separated integers:",
|
|
)
|
|
scanner.Scan()
|
|
input := strings.Fields(scanner.Text())
|
|
|
|
for _, value := range input {
|
|
num, err := strconv.Atoi(value)
|
|
if err != nil {
|
|
fmt.Printf("Invalid input: %q\n", value)
|
|
continue OuterLoop
|
|
} else {
|
|
seq = append(seq, num)
|
|
}
|
|
}
|
|
}
|
|
a := seq[:len(seq)/2]
|
|
b := seq[len(seq)/2:]
|
|
a1 := a[:len(a)/2]
|
|
a2 := a[len(a)/2:]
|
|
b1 := b[:len(b)/2]
|
|
b2 := b[len(b)/2:]
|
|
|
|
var wg sync.WaitGroup
|
|
wg.Add(4)
|
|
go BubbleSort(a1, &wg)
|
|
go BubbleSort(a2, &wg)
|
|
go BubbleSort(b1, &wg)
|
|
go BubbleSort(b2, &wg)
|
|
wg.Wait()
|
|
|
|
a = Merge(a1, a2)
|
|
b = Merge(b1, b2)
|
|
fmt.Println(strings.Trim(fmt.Sprint(Merge(a, b)), "[]"))
|
|
}
|