Break it up and read
No more classical sorting algorithms, the most likely first impression of a sort algorithm is it. I remember that the teacher took a class time to explain in detail when I was in college.
Principle
The bubbling algorithm (bubble sort) is a very simple sort of exchange. Each wheel starts with the first element, then swaps the larger value backward one bit until the entire queue is orderly.
Complexity of
As with other inefficient sorting algorithms, the average time complexity is O (n^2). The best case is that the original queue is a well-arranged array, and the time complexity is O (n). Space complexity is O (1) for Exchange.
The algorithm for sorting by comparison is stable, and so is the bubble sort.
Code
package mainimport ( "time" "fmt" "math/rand")func main() { var length = 15 var list []int // 以时间戳为种子生成随机数,保证每次运行数据不重复 r := rand.New(rand.NewSource(time.Now().UnixNano())) for i := 0; i < length; i++ { list = append(list, int(r.Intn(1000))) } fmt.Println(list) // n-1轮,每轮减少一位的比较 for i := 1; i < length; i++ { // 每轮都从第一个元素开始,将最大的值交换到最后一位 for j := 0; j < length-i; j++ { if list[j] > list[j+1] { list[j], list[j+1] = list[j+1], list[j] } } fmt.Println(list) }}
Run results