Last active
October 27, 2020 16:10
-
-
Save Bablzz/249a390775f7506f87bfadb189193df0 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
| # Best O(1) | |
| # Worst O(long n) | |
| arr = [1,2,3,4,5,6,7,10] | |
| def bs (list, elem) | |
| low = 0 | |
| high = list.length | |
| while low != high | |
| mid = (low + high) / 2 | |
| if elem == list[mid] | |
| puts "Find elem and its number in array #{mid} and equal #{list[mid]}" | |
| return mid | |
| elsif elem < list[mid] | |
| high = mid | |
| else | |
| low = mid + 1 | |
| end | |
| end | |
| return -1 | |
| end | |
| puts bs(arr, 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment