Loading... # 冒泡排序 ## Golang 实现 ```go package main import "fmt" func main() { arr := [] int16{6, 5, 3, 1, 8, 7, 2, 4} sortArr := bubbleSort(arr) fmt.Println(sortArr) } /** 用 golang 编写一个冒泡排序 */ func bubbleSort(arr []int16) []int16 { length := len(arr) //这里是次数,比如6个元素需要排5次 for i := 0; i < length; i++ { //每次都少 i 个元素需要再排序,length-1 的意思是因为是 arr[j]和 arr[j+1]比 for j := 0; j < length-1-i; j++ { if arr[j] > arr[j+1] { arr[j] = arr[j] + arr[j+1] arr[j+1] = arr[j] - arr[j+1] arr[j] = arr[j] - arr[j+1] } } /** 也可以写成下面的写法 */ //for j := 1; j < length-i; j++ { // if arr[j-1] > arr[j] { // arr[j-1] = arr[j-1] + arr[j] // arr[j] = arr[j-1] - arr[j] // arr[j-1] = arr[j-1] - arr[j] // } //} } return arr } ``` ## 图解 ![](https://s1.ax1x.com/2018/09/28/iQ6vOx.gif) ## Complexity | Name | Best | Average | Worst | Memory | Stable | Comments | | ----------------- | :----: | :-------: | :-----: | :------: | :------: | :--------- | | **Bubble sort** | n | n2 | n2 | 1 | Yes | | Last modification:September 3, 2022 © Allow specification reprint Support Appreciate the author AliPayWeChat Like 133 If you think my article is useful to you, please feel free to appreciate