golang冒泡排序

42 阅读1分钟
func main() {

	var slice = []int{1, 4, 6, 3, 2, 6, 8, 93, 2, 43}
	fmt.Println(slice)
	bubbleSort(slice)
	fmt.Println(slice)
}

// 冒泡排序 - 时间复杂度 O(n的平方)
func bubbleSort(slice []int) {
	if slice == nil || len(slice) < 2 {
		return
	}
	n := len(slice)
	for end := n - 1; end > 0; end-- {
		for j := 0; j < end; j++ {
			if slice[end] < slice[j] {
				slice[end], slice[j] = slice[j], slice[end]
			}
		}
	}
}