Created
November 7, 2016 01:51
-
-
Save nipuntalukdar/238f2977238284b71332b512fe26e39b to your computer and use it in GitHub Desktop.
Binary search in sorted 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 my_binary_search(lst, val, start, end): | |
| if start == end: | |
| if val == lst[start]: | |
| return start | |
| return -1 | |
| if val < lst[start] or val > lst[end]: | |
| return -1 | |
| if val > lst[end]: | |
| if val == lst[end]: | |
| return end | |
| elif val < lst[end]: | |
| if val == lst[start]: | |
| return start | |
| mid = start + (end - start) /2 | |
| lret = my_binary_search(lst, val, start, mid) | |
| if lret != -1: | |
| return lret | |
| rret = my_binary_search(lst, val, mid + 1, end) | |
| return rret | |
| position = my_binary_search('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'Y', 0, 25) | |
| print position |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment