Created
August 2, 2013 09:22
-
-
Save emre/6138594 to your computer and use it in GitHub Desktop.
binary search implementation
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
| # -*- coding: utf8 -*- | |
| def binary_search(l, value): | |
| """ (list, object) -> int | |
| >>> binary_search([1, 2, 3, 4, 5], 3) | |
| 2 | |
| >>> binary_search([1, 2, 3, 4, 5], 5) | |
| 4 | |
| >>> binary_search([1, 2, 3, 4, 5], 8) | |
| -1 | |
| """ | |
| start_index = 0 | |
| end_index = len(l) - 1 | |
| while(start_index <= end_index): | |
| m = (start_index + end_index) // 2 | |
| if l[m] < value: | |
| start_index = m + 1 | |
| else: | |
| end_index = m - 1 | |
| if start_index == len(l) or l[start_index] != value: | |
| return -1 | |
| else: | |
| return start_index | |
| if __name__ == '__main__': | |
| import doctest | |
| doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment