Ex_GoAlgorithms/main.go

90 lines
1.6 KiB
Go
Raw Normal View History

2024-05-30 11:50:30 +04:00
package main
import "fmt"
func main() {
list := []int{5, 4, 0, 9, 7, 1, 3, 2, 4}
fmt.Printf("Список до сортировки - %d\n", list)
//sortedList := BubbleSort(list)
//sortedList := MergeSort(list)
sortedList := QuickSort(list)
fmt.Printf("Список после сортировки - %d", sortedList)
}
func BubbleSort(list []int) []int {
for i := 0; i < len(list); i++ {
for j := 0; j < len(list)-i-1; j++ {
if list[j] > list[j+1] {
temp := list[j]
list[j] = list[j+1]
list[j+1] = temp
}
}
}
return list
}
func MergeSort(items []int) []int {
if len(items) < 2 {
return items
}
middle := len(items) / 2
left := MergeSort(items[:middle])
right := MergeSort(items[middle:])
return Merge(left, right)
}
func Merge(left, right []int) []int {
var result []int
i := 0
j := 0
for i < len(left) && j < len(right) {
if left[i] < right[j] {
result = append(result, left[i])
i++
} else {
result = append(result, right[j])
j++
}
}
for ; i < len(left); i++ {
result = append(result, left[i])
}
for ; j < len(right); j++ {
result = append(result, right[j])
}
return result
}
func QuickSort(arr []int) []int {
if len(arr) <= 1 {
return arr
}
pivot := arr[len(arr)/2]
left := make([]int, 0)
middle := make([]int, 0)
right := make([]int, 0)
for _, item := range arr {
if item < pivot {
left = append(left, item)
} else if item == pivot {
middle = append(middle, item)
} else {
right = append(right, item)
}
}
return append(
append(QuickSort(left), middle...),
QuickSort(right)...,
)
}