Created
          October 12, 2012 00:23 
        
      - 
      
 - 
        
Save BrianJoyce/3876603 to your computer and use it in GitHub Desktop.  
    binary_search_fail
  
        
  
    
      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
    
  
  
    
  | =begin | |
| Given an array and a number that we are looking for | |
| Find midpoint of array | |
| is number equal to the midpoint? | |
| return index of number | |
| Is it greater? | |
| set midpoint + 1 as new_min | |
| recurse | |
| Is it less? | |
| set midpoint - 1 as new_max | |
| recurse | |
| end | |
| =end | |
| def binary_search(number, array, min = 0, max = array.length) | |
| midpoint = (min + max) / 2 | |
| if number == array[midpoint] | |
| return midpoint | |
| elsif number > array[array.length-1] | |
| return "-1" | |
| elsif number < array[0] | |
| return "-1" | |
| elsif number > array[midpoint] | |
| min = midpoint + 1 | |
| elsif number < array[midpoint] | |
| max = midpoint - 1 | |
| elsif midpoint > | |
| end | |
| binary_search(number, array, min, max) | |
| #35 4.5 7 | |
| end | |
| test_array = (100..200).to_a | |
| puts binary_search(135, test_array) == 35 | |
| # => true | |
| test_array = [13, 19, 24, 29, 32, 37, 43] | |
| puts binary_search(35, test_array) == -1 | |
| # => true | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment