Created
November 14, 2013 06:55
-
-
Save adamloo85/7462570 to your computer and use it in GitHub Desktop.
Binary search method that searches through a passed array. Takes two parameters, number to be searched and data array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def binary_search(num, arr) | |
| high = arr.length - 1 | |
| low = 0 | |
| while low < high | |
| mid = (low + high) / 2 | |
| if arr[mid] > num | |
| low = mid + 1 | |
| elsif arr[mid] < num | |
| high = mid - 1 | |
| elsif arr[mid] == num | |
| return mid | |
| end | |
| end | |
| return -1 if low == high | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment