A simple example of ruby Implementing a binary search (binary lookup) algorithm _ruby Special topics

Source: Internet
Author: User

In computer science, binary search (English: Binary search), also known as binary search (English: Half-interval search), logarithmic search (English: Logarithmic search), is an ordered array to find a certain element of the search algorithm. The search process begins with an intermediate element of an array, and if the middle element is exactly the element to find, the search completes, and if a particular element is greater or less than the intermediate element, it is found in the half of the array that is greater than or less than the middle element, and is compared with the middle element as If an array of steps is empty, the representation cannot be found. Each comparison of this search algorithm narrows the search range by half.

Degree of complexity analysis
Complexity of Time:
binary search reduces the search area by half each time, and the complexity of the times. (n represents the number of elements in the collection)
Complexity of space:
Although it is defined recursively, the tail recursion can be rewritten as a loop.

Ruby code example

def binseaech (arr, i) low
  , high = 0, arr.size-1 while
  (Low < high)
    mid = (low + high)/2
    if Arr[mid] & Lt I low
      = mid + 1
    elsif Arr[mid] > I high
      = Mid-1
    else return mid end
end
  arr = [1,3,12,34,35,46,91,108]
puts Binseaech (arr, 91)

Results:

6
[finished in 0.1s]

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.