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.
Half search reduces the search area by half each time, and the time complexity is。 (n represents the number of elements in the set)
Although defined in recursive form, tail recursion can be rewritten as a loop.
Ruby code example