Last active
July 9, 2018 20:50
-
-
Save accessnash/bf11ee19cc050b3ab760c811acb99e7d to your computer and use it in GitHub Desktop.
Binary search algorithm with a measurement of performance in terms of time taken
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
| from time import time | |
| def present(collection, num): | |
| '''finds out if number of our interest is present in collection''' | |
| return num in collection | |
| def binsearch(ordered, num): | |
| '''binary search function to show position of number of our interest in the collection''' | |
| low = 0 | |
| high = len(ordered)-1 | |
| while low<= high: | |
| mid = round((low + high)/2) | |
| if num == ordered[mid]: | |
| return True | |
| elif num < ordered[mid]: | |
| high = mid - 1 | |
| else: | |
| low = mid + 1 | |
| return -(low + 1) | |
| def insertqueue(ordered, num): | |
| '''inserts the number of interest in its proper location''' | |
| index = binsearch(ordered, num) | |
| if index < 0: | |
| list(ordered).insert(-(index + 1), num) | |
| return | |
| list(ordered).insert(index, num) | |
| def performance(): | |
| '''function measures performance in terms of time of inserting operation''' | |
| n = 1024 | |
| while n < 10000000: | |
| sorted = range(n) | |
| now = time() | |
| insertqueue(sorted, n + 1) | |
| done = time() | |
| print(n, (done-now)*1000) | |
| n *= 2 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://nashstatistica.wordpress.com/2018/07/09/binary-search-algorithm/