-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_search.go
43 lines (39 loc) · 1.07 KB
/
binary_search.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
package searches
// BinarySearchByRecur 二分查找法递归实现
//
// 二分查找算法(binary search)又称折半搜索(half-interval search)
// 用于在有序数组中查找特定元素的搜索算法
// 注意给定数组必须是升序排列的
//
// References: https://en.wikipedia.org/wiki/Binary_search_algorithm
func BinarySearchByRecur(items []int, target int) int {
return binarySearchByRecur(items, target, 0, len(items)-1)
}
func binarySearchByRecur(items []int, target, low, high int) int {
if low > high {
return -1
}
mid := low + (high-low)/2
if items[mid] == target {
return mid
} else if items[mid] > target {
return binarySearchByRecur(items, target, low, mid-1)
} else {
return binarySearchByRecur(items, target, mid+1, high)
}
}
// BinarySearch 二分查找法的非递归实现
func BinarySearch(items []int, target int) int {
low, high := 0, len(items)-1
for low <= high {
mid := low + (high-low)/2
if items[mid] > target {
high = mid - 1
} else if items[mid] < target {
low = mid + 1
} else {
return mid
}
}
return -1
}