Created
May 31, 2020 19:29
-
-
Save EvanBrightside/180ec748c80a0bdd41922d69846691e8 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
| def binary_search(arr, value) | |
| floor = 0 | |
| ceiling = arr.length - 1 | |
| counter = 0 | |
| winner = nil | |
| while floor <= ceiling | |
| counter +=1 | |
| guess = (floor + ceiling)/ 2 | |
| print "Attempt #{counter}: " | |
| if arr[guess] == value | |
| winner = guess | |
| puts "Index ##{guess} is right!" | |
| break | |
| elsif arr[guess] < value | |
| puts "Too low. Guess higher." | |
| floor = guess + 1 | |
| else | |
| puts "Too high. Guess lower." | |
| ceiling = guess - 1 | |
| end | |
| end | |
| puts "Your number is not in array" unless winner | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment