Simple example of binary search (binary search) algorithm implemented by ruby

Time:2021-11-18

In computer science, binary search, also known as half interval search and logarithmic search, is a search algorithm for finding a specific element in an ordered array. The search process starts from the middle element of the array. If the middle element is exactly the element to be found, the search process ends; If a specific element is greater than or less than the intermediate element, it is searched in the half of the array that is greater than or less than the intermediate element, and the comparison starts from the intermediate element as at the beginning. If the array is empty in a step, it means it cannot be found. Each comparison of this search algorithm reduces the search scope by half.

Complexity analysis
Time complexity:
Half search reduces the search area by half each time, and the time complexity isSimple example of binary search (binary search) algorithm implemented by ruby。 (n represents the number of elements in the set)
Space complexity:
Simple example of binary search (binary search) algorithm implemented by rubyAlthough defined in recursive form, tail recursion can be rewritten as a loop.

Ruby code example

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def binseaech(arr, i)
  low, high = 0, arr.size - 1
  while (low < high)
    mid = (low + high)/2
    if arr[mid] < i
      low = mid + 1
    elsif arr[mid] > i
      high = mid - 1
    else
      return mid
    end
  end
end
 
arr = [1,3,12,34,35,46,91,108]
puts binseaech(arr, 91)

result:

?
1
2
6
[Finished in 0.1s]