Binary search in Python

The code for the binary search is below.

def binary_search(src, target_value):
    result = False
    lower_index = 0
    higher_index = len(src)-1
    while True:
        dst = src[lower_index:higher_index+1]
        medium_index = (lower_index + higher_index) // 2

        if src[medium_index] == target_value:
            result = True
            break

        if (higher_index - lower_index) == 1:
            break

        if target_value >= dst[medium_index]:
            lower_index = medium_index
        else:
            higher_index = medium_index
    return result


def main():
    src = [1, 2, 3, 4, 5, 6]  #Already sorted
    target_value = 4

    if binary_search(src, target_value):
        print('Found!')
    else:
        print('Not Found')


if __name__ == '__main__':
    main()

The execution result is as follows.

Found!

Thank you for reading until the end. Let's meet again.

Recommended Posts

Binary search in Python
Binary search in Python (binary search)
Binary search in Python / C ++
Algorithm in Python (binary search)
Write a binary search in Python
Binary search (python2.7) memo
[Python] Binary search ABC155D
Linear search in Python
Binary search with python
Binary search with Python3
Search for strings in Python
Algorithm in Python (breadth-first search, bfs)
Save the binary file in Python
Create a binary file in Python
Algorithm in Python (depth-first search, dfs)
Write a depth-first search in Python
Depth-first search using stack in Python
Quadtree in Python --2
Python in optimization
CURL in python
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
visualize binary search
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
ABC146C (binary search)
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Algorithm learned with Python 10th: Binary search