程序由Golang实现,代码如下:
1.使用递归实现二分查找
//使用递归进行二分查找 func binarySearchTest() { //二分查找的数组必须是已经排好序的 nums := []int{1, 3, 5, 6, 7, 10, 12, 15, 17, 18, 19, 20, 21} value := 2 var index int = searchIndex(nums, value) fmt.Println("index:", index) } //在nums中查找元素value,返回index func searchIndex(nums []int, value int) int { return searchIndexInArea(nums, value, 0, len(nums)-1) } //在nums中查找元素value,返回index. 其中index位于[left,right]之间 func searchIndexInArea(nums []int, value int, left int, right int) int { if left > right { return -1 } mid := left + (right-left)/2 if nums[mid] < value { return searchIndexInArea(nums, value, mid+1, right) } else if nums[mid] > value { return searchIndexInArea(nums, value, left, mid-1) } return mid }
2.使用循环实现二分查找
func searchIndex2(nums []int, value int) int { left, right := 0, len(nums)-1 for left <= right { mid := left + (right-left)/2 if nums[mid] < value { left = mid + 1 } else if nums[mid] > value { right = mid - 1 } else { return mid } } return -1 }
时间: 2024-10-04 06:47:10