Created
March 26, 2013 00:51
-
-
Save reterVision/5242252 to your computer and use it in GitHub Desktop.
Binary Search in Python
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
| #!/usr/bin/python | |
| """ | |
| Binary Search | |
| """ | |
| def bsearch(array, min, max, target): | |
| if max < min: | |
| return -1 | |
| mid = (max + min) / 2 | |
| if array[mid] == target: | |
| return mid | |
| elif array[mid] > target: | |
| return bsearch(array, min, mid-1, target) | |
| elif array[mid] < target: | |
| return bsearch(array, mid+1, max, target) | |
| def main(): | |
| l = range(0, 10) | |
| print l | |
| result = bsearch(l, 0, len(l)-1, 9) | |
| print 'Search for {0}, result: {1}'.format(9, result) | |
| result = bsearch(l, 0, len(l)-1, 0) | |
| print 'Search for {0}, result: {1}'.format(0, result) | |
| result = bsearch(l, 0, len(l)-1, 6) | |
| print 'Search for {0}, result: {1}'.format(6, result) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment