Binary Search

Find the index of an element in a sorted array using binary search with O(log n) time complexity.

Code

Algorithms
i = arr.bsearch_index { |x| x >= target }
return (i && arr[i] == target) ? i : -1

Parameters

Sorted array

Element to find

Server

More Ruby Snippets