本教程讲解在 golang 中创建冒泡排序,冒泡排序是一个经典的排序算法,元素将根据要求进行交换,并逐个下降到最后一个元素。在第一阶段结束时,最后一个元素就是列表中最大的元素。其遵循以下规则:

a[0] > a[1]a[0] < a[1]a[1] 和 a[2]
Ω(n)O(n^2)
package main
import (
  "fmt"
  _ "os"
)
func main() {
  a := []int{31, 8, 6, 54, 95, 84, 71, 67}
  fmt.Printf("%v\n", a)
  len_arr := len(a) - 1
  fmt.Printf("数组长度 : %v\n", len_arr)
  for i := 0; i < len_arr; i++ {
    for j := 0; j < len_arr-i; j++ {
      fmt.Printf("first index:%v The value : %v\n", a[j], a[j+1])
      if a[j] > a[j+1] {
        tmp := a[j]
        a[j] = a[j+1]
        a[j+1] = tmp
      }
    }
    fmt.Println("迭代次数=======================", i+1)
    fmt.Printf("\n当前迭代完成后数组 : %v\n", a)
  }
  fmt.Printf("最终排序完成数组 : %v", a)
}

输出

[31 8 6 54 95 84 71 67]
数组长度 : 7
first index:31 The value : 8
first index:31 The value : 6
first index:31 The value : 54
first index:54 The value : 95
first index:95 The value : 84
first index:95 The value : 71
first index:95 The value : 67
迭代次数======================= 1

当前迭代完成后数组 : [8 6 31 54 84 71 67 95]
first index:8 The value : 6
first index:8 The value : 31
first index:31 The value : 54
first index:54 The value : 84
first index:84 The value : 71
first index:84 The value : 67
迭代次数======================= 2

当前迭代完成后数组 : [6 8 31 54 71 67 84 95]
first index:6 The value : 8
first index:8 The value : 31
first index:31 The value : 54
first index:54 The value : 71
first index:71 The value : 67
迭代次数======================= 3

当前迭代完成后数组 : [6 8 31 54 67 71 84 95]
first index:6 The value : 8
first index:8 The value : 31
first index:31 The value : 54
first index:54 The value : 67
迭代次数======================= 4

当前迭代完成后数组 : [6 8 31 54 67 71 84 95]
first index:6 The value : 8
first index:8 The value : 31
first index:31 The value : 54
迭代次数======================= 5

当前迭代完成后数组 : [6 8 31 54 67 71 84 95]
first index:6 The value : 8
first index:8 The value : 31
迭代次数======================= 6

当前迭代完成后数组 : [6 8 31 54 67 71 84 95]
first index:6 The value : 8
迭代次数======================= 7

当前迭代完成后数组 : [6 8 31 54 67 71 84 95]
最终排序完成数组 : [6 8 31 54 67 71 84 95]