Algorithm: two methods (recursion/loop) implement binary search

Source: Internet
Author: User

Algorithm: two methods (recursion/loop) implement binary search

The program is implemented by Golang. The Code is as follows:

1. implement binary search using recursion

 

// Recursive Binary Search func binarySearchTest () {// The binary search array must be sorted nums: = [] int {1, 3, 5, 6, 7, 10, 12, 15, 17, 18, 19, 20, 21} value: = 2var index int = searchIndex (nums, value) fmt. println ("index:", index)} // search for the element value in nums and return indexfunc searchIndex (nums [] int, value int) int {return searchIndexInArea (nums, value, 0, len (nums)-1)} // search for the element value in nums and Return index. where index is located between [left, right] func searchIndexInArea (nums [] int, value int, left int, right int) int {if left> right {return-1} mid: = left + (right-left)/2if 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. implement binary search using Loops

 

 

func searchIndex2(nums []int, value int) int {left, right := 0, len(nums)-1for left <= right {mid := left + (right-left)/2if nums[mid] < value {left = mid + 1} else if nums[mid] > value {right = mid - 1} else {return mid}}return -1}



 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.