[PYTHON] visualize binary search

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")

Output

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

Recommended Posts

visualize binary search
ABC146C (binary search)
Binary search in Python
Binary search (python2.7) memo
[Python] Binary search ABC155D
Binary search with python
Binary search with Python3
Binary search in Python (binary search)
C language ALDS1_4_B Binary Search
Binary search in Python / C ++
Algorithm in Python (binary search)
Write a binary search in Python
Get and visualize google search trends
Binary search summary for competition professionals
[C language algorithm] Binary search tree
Algorithm learned with Python 10th: Binary search
django search
Algorithm in Python (ABC 146 C Binary Search
Binary method
Django search
Confirmation of basic matters of competition professional ~ Binary search ~
[At Coder] Solve the problem of binary search