-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsertion_sort.go
62 lines (55 loc) · 1.1 KB
/
insertion_sort.go
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
57
58
59
60
61
62
package main
import (
"flag"
"fmt"
"strconv"
)
func insertionSort(source []int, show, desc bool) {
if show {
fmt.Println("start sort:", source)
fmt.Println()
}
for i := 1; i < len(source); i++ {
key := source[i]
if show {
fmt.Println("now insert index", i, "value", key)
}
j := i - 1
if desc {
for ; j >= 0 && source[j] < key; j-- {
if show {
fmt.Println("index:", j, "value:", source[j], "back 1 position")
}
source[j+1] = source[j]
}
} else {
for ; j >= 0 && source[j] > key; j-- {
if show {
fmt.Println("index:", j, "value:", source[j], "back 1 position")
}
source[j+1] = source[j]
}
}
if show && j == i-1 {
fmt.Println("keep status quo")
}
source[j+1] = key
if show {
fmt.Println("status:", source)
fmt.Println()
}
}
return
}
func main() {
show := flag.Bool("s", false, "show detail flag")
desc := flag.Bool("d", false, "desc flag")
flag.Parse()
source := []int{}
for _, arg := range flag.Args() {
i, _ := strconv.Atoi(arg)
source = append(source, i)
}
insertionSort(source, *show, *desc)
fmt.Println(source)
}