Created
October 11, 2012 20:13
-
-
Save arn-e/3875193 to your computer and use it in GitHub Desktop.
binary search
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
| #binary search | |
| def binary_search(item,array,min = 0,max = array.length, half = (min + max) / 2) | |
| return min if item == array[min] | |
| return -1 if (item < array[0] || item > array[array.length-1]) || (min == max - 1) | |
| item < array[half] ? binary_search(item,array,min,half) : binary_search(item,array,half,array.length) | |
| end | |
| test_array = (1..15).to_a | |
| puts binary_search(13,test_array) == 12 | |
| test_array = (100..200).to_a | |
| puts binary_search(135, test_array) == 35 | |
| test_array = [13, 19, 24, 29, 32, 37, 43] | |
| puts binary_search(35, test_array) == -1 | |
| test_array = [-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7] | |
| puts binary_search(-3, test_array) == 2 | |
| puts binary_search(3, test_array) == 8 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment