Skip to content

Commit 0e24bb9

Browse files
author
hero
committed
二分查找,快排
1 parent 808fc02 commit 0e24bb9

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package standard_library
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func BinarySearch(data []int, f int) int {
8+
var (
9+
left = 0
10+
right = len(data) - 1
11+
)
12+
for left <= right {
13+
mod := (right + left) / 2
14+
if data[mod] > f {
15+
right = mod - 1
16+
} else if data[mod] < f {
17+
left = mod + 1
18+
} else {
19+
return mod
20+
}
21+
}
22+
return -1
23+
}
24+
25+
func QSort(d []int) {
26+
if len(d) <= 1 {
27+
return
28+
}
29+
var (
30+
left = 0
31+
right = len(d) - 1
32+
)
33+
start := d[0]
34+
for left < right {
35+
if start > d[left+1] {
36+
d[left], d[left+1] = d[left+1], d[left]
37+
left++
38+
} else {
39+
d[left+1], d[right] = d[right], d[left+1]
40+
right--
41+
}
42+
}
43+
QSort(d[:left])
44+
QSort(d[left+1:])
45+
}
46+
47+
func Test_BinarySearch(t *testing.T) {
48+
var a = []int{3, 2, 1, 9, 7, 4, 7, 6}
49+
QSort(a)
50+
t.Log(a)
51+
t.Log(BinarySearch([]int{1, 2, 3, 4, 5, 6, 7, 8}, 3))
52+
}

0 commit comments

Comments
 (0)