冒泡排序的原理:对于一个数组里所有的元素进行两两比较,发生大于则变换数组下标则为升序排序,发生小于则变换数据下标的则为降序排序
源码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
| package main
import (
"fmt"
"math/rand"
"time"
)
const (
num = 10
rangeNum = 100000
)
func main() {
randSeed := rand.New(rand.NewSource(time.Now().Unix() + time.Now().UnixNano()))
var buf []int
for i := 0; i < num; i++ {
buf = append(buf, randSeed.Intn(rangeNum))
}
fmt.Println(buf)
t := time.Now()
//冒泡排序
bubble(buf)
fmt.Println(buf)
fmt.Println(time.Since(t))
}
// 冒泡排序
func bubble(buf []int) {
times := 0
for i := 0; i < len(buf)-1; i++ {
flag := false
for j := 1; j < len(buf)-i; j++ {
if buf[j-1] > buf[j] {
times++
tmp := buf[j-1]
buf[j-1] = buf[j]
buf[j] = tmp
flag = true
}
}
if !flag {
break
}
}
fmt.Println("bubble times: ", times)
}
|
1
2
3
4
5
| midoksdeMacBook-Pro:test midoks$ go run bubble.go
[69297 59940 47374 33333 33333 28778 5651 91336 44321 46186]
bubble times: 28
[5651 28778 33333 33333 44321 46186 47374 59940 69297 91336]
6.261µs
|