Created
January 19, 2016 06:10
-
-
Save Shaunwei/7cb8b38de53b5757643b to your computer and use it in GitHub Desktop.
Algorithm Post: Binary Search - Search for a range
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
| class BinarySearch: | |
| @staticmethod | |
| def find_first_position(arr, target): | |
| st, ed = 0, len(arr) - 1 | |
| while st + 1 < ed: | |
| mid = (st + ed) / 2 | |
| if arr[mid] == target: | |
| ed = mid | |
| elif arr[mid] < target: | |
| st = mid | |
| else: | |
| ed = mid | |
| if arr[st] == target: | |
| return st | |
| if arr[ed] == target: | |
| return ed | |
| return -1 | |
| @staticmethod | |
| def find_last_position(arr, target): | |
| st, ed = 0, len(arr) - 1 | |
| while st + 1 < ed: | |
| mid = (st + ed) / 2 | |
| if arr[mid] == target: | |
| st = mid | |
| elif arr[mid] < target: | |
| st = mid | |
| else: | |
| ed = mid | |
| if arr[ed] == target: | |
| return ed | |
| if arr[st] == target: | |
| return st | |
| return -1 | |
| if __name__ == '__main__': | |
| arr = [1, 2, 3, 3, 3, 4, 5] | |
| print(BinarySearch.find_first_position(arr, 3)) | |
| print(BinarySearch.find_last_position(arr, 3)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment