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]