/* 冒泡排序 */ func bubbleSorter(array []int) { //用于交换数int据的暂存单元 var temp int //将数组的最大索引视为水面, for i := len(array) - 1; i >= 0; i-- { //数组的最小索引视为水底 //i每减少1,就有一个气泡上升到最终位置。所以只需要对1到i之间的元素进行排序即可。 for j := 1; j <= i; j++ { if array[j-1] > array[j] { temp = array[j-1] array[j-1] = array[j] array[j] = temp } } } } func main() { array := []int{6, 5, 4, 9, 8, 3, 7, 2, 1} bubbleSorter(array) fmt.Println(array) }