Skip to content

Instantly share code, notes, and snippets.

@giwa
Created January 7, 2016 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giwa/eb62914560fb09c634d3 to your computer and use it in GitHub Desktop.
Save giwa/eb62914560fb09c634d3 to your computer and use it in GitHub Desktop.
import random
import math
def bs_print(elements, low, high, middle):
"""
visulize binary search process
"""
es = elements.copy()
ms = es[middle]
es.insert(high + 1, ']')
es.insert(low, '[')
formatted_elements = " ".join(map(lambda x: str(x), es))
arrow = [" " * len(str(e)) for e in es]
arrow[middle+1] = "I".center(len(arrow[middle+1]))
formatted_arrow = " ".join(arrow)
print("low: %d, high: %d, middle: %d, x: %d" % (low, high, middle, ms))
print(formatted_elements)
print(formatted_arrow)
def bsearch(l, x):
low = 0
high = len(l) - 1
while low <= high:
middle = math.ceil((low + high) / 2)
bs_print(l, low, high, middle)
if l[middle] == x:
return True
elif x > l[middle]:
low = middle + 1
else:
high = middle -1
return False
def random_elements():
r = [random.choice([i for i in range(20)]) for r in range(41)]
r.sort()
return r
if bsearch(random_elements(), 6):
print("Hit")
low: 0, high: 40, middle: 20, x: 10
[ 0 0 0 1 1 1 2 3 3 3 4 5 6 8 8 8 9 10 10 10 10 10 11 11 12 12 12 12 12 13 13 14 15 15 16 16 16 17 18 19 19 ]
I
low: 0, high: 19, middle: 10, x: 4
[ 0 0 0 1 1 1 2 3 3 3 4 5 6 8 8 8 9 10 10 10 ] 10 10 11 11 12 12 12 12 12 13 13 14 15 15 16 16 16 17 18 19 19
I
low: 11, high: 19, middle: 15, x: 8
0 0 0 1 1 1 2 3 3 3 4 [ 5 6 8 8 8 9 10 10 10 ] 10 10 11 11 12 12 12 12 12 13 13 14 15 15 16 16 16 17 18 19 19
I
low: 11, high: 14, middle: 13, x: 8
0 0 0 1 1 1 2 3 3 3 4 [ 5 6 8 8 ] 8 9 10 10 10 10 10 11 11 12 12 12 12 12 13 13 14 15 15 16 16 16 17 18 19 19
I
low: 11, high: 12, middle: 12, x: 6
0 0 0 1 1 1 2 3 3 3 4 [ 5 6 ] 8 8 8 9 10 10 10 10 10 11 11 12 12 12 12 12 13 13 14 15 15 16 16 16 17 18 19 19
I
Hit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment