查找算法——二分查找
1、算法介绍
(1)序列必须是有序的
(2)取序列的中间元素与查找值比较,相等返回元素下标
(3)根据序列升序或降序,中间元素小于或大于查找值的具体情况,选择中间元素右边或左边的序列重复步骤(2)(3),
未找到返回-1。
2、代码实现
2.1、golang
package main import ( "fmt" ) func main() { slice := []int{1, 2, 3, 4, 5, 6} //升序序列 key := 4 index := SearchBinary(slice, key) if index == -1 { fmt.Printf("%v不存在元素%v\n", slice, key) } else { fmt.Printf("%v位于%v下标为%v的位置。\n", key, slice, index) } } //二分查找 func SearchBinary(slice []int, key int) int { left, right := 0, len(slice)-1 for left <= right { mid := (left + right) / 2 if slice[mid] == key { return mid } if slice[mid] > key { right = mid - 1 } if slice[mid] < key { left = mid + 1 } } return -1 }
2.2、python3
# 二分查找 def search_binary(arr, key): left, right = 0, len(arr) - 1 while (left <= right): mid = (left + right) // 2 if (arr[mid] == key): return mid if (arr[mid] > key): right = mid - 1 if (arr[mid] < key): left = mid + 1 return -1 # 递归二分查找 def search_binary2(arr, key, left, right): if (left > right): return -1 mid = (left + right) // 2 if (arr[mid] == key): return mid if (arr[mid] > key): return search_binary2(arr, key, left, mid - 1) if (arr[mid] < key): return search_binary2(arr, key, mid + 1, right) if __name__ == '__main__': arr = [1, 2, 3, 4, 5, 6] key = 6 # index = search_binary(arr, key) index = search_binary2(arr, key, 0, len(arr) - 1) if index == -1: print("%s不存在元素%s。" % (arr, key)) else: print("%s位于%s下标为%s的位置。" % (key, arr, index))