基本排序算法的Golang实现
BubbleSort
func BubbleSort(data []int) {
fmt.Println("BubbleSort")
fmt.Printf("Source Data:%d\n", data)
for i := 0; i < len(data); i++ {
for j := 0; j < len(data)-i-1; j++ {
if data[j] > data[j+1] {
data[j], data[j+1] = data[j+1], data[j]
}
}
fmt.Printf("Middle Data:%2d=>%d\n", i, data)
}
fmt.Printf("Result Data:%d\n", data)
}
InsertSort
func InsertSort(data []int) {
fmt.Println("InsertSort")
fmt.Printf("Source Data:%d\n", data)
for i := 1; i < len(data); i++ {
if data[i] < data[i-1] {
for j := i; j > 0; j-- {
if data[j] < data[j-1] {
data[j-1], data[j] = data[j], data[j-1]
}
}
}
fmt.Printf("Middle Data:%2d=>%d\n", i, data)
}
fmt.Printf("Result Data:%d\n", data)
}
SelectSort
func SelectSort(data []int) {
fmt.Println("SelectSort")
fmt.Printf("Source Data:%d\n", data)
for i := 0; i < len(data); i++ {
for j := i + 1; j < len(data); j++ {
if data[i] > data[j] {
data[j], data[i] = data[i], data[j]
}
}
fmt.Printf("Middle Data:%2d=>%d\n", i, data)
}
fmt.Printf("Result Data:%d\n", data)
}
有疑问加站长微信联系(非本文作者)
![](https://static.golangjob.cn/static/img/footer.png?imageView2/2/w/280)