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: