希尔排序(Shell’s Sort)是插入排序的一种又称“缩小增量排序”(Diminishing Increment Sort),是直接插入排序算法的一种更高效的改进版本。希尔排序是非稳定排序算法。该方法因D.L.Shell于1959年提出而得名。
源码
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
48
49
50
51
52
53
54
55
56
| package main
import (
"fmt"
"math/rand"
"time"
)
const (
num = 10
rangeNum = 10
)
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))
}
t := time.Now()
// 选择排序
shellSort(buf)
fmt.Println(buf)
fmt.Println(time.Since(t))
}
// 希尔排序
func shellSort(buf []int) {
times := 0
tmp := 0
length := len(buf)
incre := length
for {
incre /= 2
for k := 0; k < incre; k++ {
for i := k + incre; i < length; i += incre {
for j := i; j > k; j -= incre {
times++
if buf[j] < buf[j-incre] {
tmp = buf[j-incre]
buf[j-incre] = buf[j]
buf[j] = tmp
} else {
break
}
}
}
}
if incre == 1 {
break
}
}
fmt.Println("shell's sort times: ", times)
}
|
1
2
3
4
| midoksdeMacBook-Pro:test midoks$ go run ss.go
shell's sort times: 27
[0 1 4 4 4 5 6 6 8 8]
59.205µs
|