Golang实现冒泡排序算法(Bubble Sort)


本文将使用Go语言完成冒泡排序算法(Bubble Sort)的实现;

Golang冒泡排序(Bubble Sort)

package main

import(
	"fmt"
)
func bubbleSort(arr []int) []int {
	swapped := true
	for swapped {
		swapped = false
		for i := 0; i < len(arr)-1; i++ {
			if arr[i+1] < arr[i] {
				arr[i+1], arr[i] = arr[i], arr[i+1]
				swapped = true
			}
		}
	}
	return arr
}

func main(){
	lst := []int{-10,2,5,13,7,-1,21,1,3,2,0,-5,9,6,7}
	fmt.Printf("排序前:%v\n",lst)
	fmt.Printf("排序后:%v\n",bubbleSort(lst))
}

运行效果

排序前:[-10 2 5 13 7 -1 21 1 3 2 0 -5 9 6 7]
排序后:[-10 -5 -1 0 1 2 2 3 5 6 7 7 9 13 21]

如需转载,请注明出处;本文地址:https://www.perfcode.com/p/golang-bubble-sort.html