package main
import "fmt"
/*
*
冒泡排序
*/
func main() {
var arr = []int{5, 8, 4, 9, 1, 3, 4, 7}
for i := len(arr) - 1; i >= 1; i-- {
var flag bool = false
for j := 0; j < i; j++ {
if arr[j] > arr[j+1] {
var num int = arr[j+1]
arr[j+1] = arr[j]
arr[j] = num
flag = true
}
}
if !flag {
break
}
}
fmt.Println(arr)
}
选择排序
package main
import "fmt"
/*
选择排序
*/
func main() {
var arr = []int{5, 8, 4, 9, 1, 3, 4, 7}
_ = arr
for i := 0; i < len(arr); i++ {
var minIndex = i
for j := i + 1; j < len(arr); j++ {
if arr[j] < arr[minIndex] {
minIndex = j
}
}
var tmp = arr[i]
arr[i] = arr[minIndex]
arr[minIndex] = tmp
}
fmt.Println(arr)
}
插入排序
package main
import "fmt"
/*
插入排序
*/
func main() {
var arr = []int{5, 8, 4, 9, 1, 3, 4, 7}
for i := 1; i <= len(arr)-1; i++ {
var tmp = arr[i]
var index = i
for j := i - 1; j >= 0; j-- {
if tmp < arr[j] {
arr[j+1] = arr[j]
index = j
} else {
break
}
arr[index] = tmp
}
}
fmt.Println(arr)
}
希尔排序
package main
import "fmt"
/*
希尔排序
*/
func main() {
var arr = []int{5, 8, 4, 9, 1, 3, 4, 7}
_ = arr
for gap := len(arr) / 2; gap > 0; gap = gap / 2 {
for i := gap; i < len(arr); i = i + gap {
var tmp = arr[i]
var index = i
for j := i - gap; j >= 0; j = j - gap {
if tmp < arr[j] {
arr[j+gap] = arr[j]
index = j
} else {
break
}
}
arr[index] = tmp
}
}
fmt.Println(arr)
}