go-数据结构[12]-二分查找

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
63
64
65
66
67
package main

import "fmt"

func main() {

arr:= []int{1,3,4,6,7,8,10,13,14}


for index,data:= range arr{
i:= binarySearch(arr,data)
fmt.Printf("实际序号:%d,找到序号为:%d\n",index,i)

}

fmt.Println("-------------------------")
for index,data:= range arr{
i:= binarySearch2(arr,0,len(arr)-1,data)
fmt.Printf("实际序号:%d,找到序号为:%d\n",index,i)

}

}



func binarySearch( arr []int, data int ) int{


low:= 0
high:= len(arr) - 1

for low <= high{
mid:= low + (high-low)/2

if data > arr[mid]{
low= mid+1
}else if data < arr[mid]{
high= mid - 1
}else{
return mid
}
}

return -1
}



func binarySearch2( arr []int,low,high, data int ) int{

ret:= -1
if low <= high{
mid := low + (high-low)/2

if data > arr[mid]{
ret = binarySearch2(arr,mid+1,high,data)
}else if data < arr[mid]{
ret = binarySearch2(arr,low,mid-1,data)
}else{
return mid
}
}


return ret
}