Ruby: a simple example of Binary Search (Binary Search) algorithm.

Source: Internet
Author: User

Ruby: a simple example of Binary Search (Binary Search) algorithm.

In computer science, binary search (English: binary search), also known as binary search (English: half-interval search), and log search (English: logarithmic search ), it is a search algorithm used to search for a specific element in an ordered array. The search process starts from the intermediate element of the array. If the intermediate element is the element to be searched, the search process ends. If a specific element is greater than or less than the intermediate element, search in the half where the array is greater than or less than the intermediate element, and compare it from the intermediate element as before. If the array in a step is empty, it indicates that no value can be found. This search algorithm reduces the search range by half for each comparison.

Complexity Analysis
Time Complexity:
Half-fold search reduces the search area by half each time, and the time complexity is. (N indicates the number of elements in the set)
Spatial complexity:
Although defined in recursion form, tail recursion can be rewritten as a loop.

Ruby sample code

Def binseaech (arr, I) low, high = 0, arr. size-1 while (low  

Result:

6 [Finished in 0.1 s]

Related Article

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.