LoginSignup
0
0

More than 3 years have passed since last update.

Pythonで二分探索

Posted at

二分探索のコードは以下です。

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]  # すでにソート済み
    target_value = 4

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


if __name__ == '__main__':
    main()

実行結果は以下になります。

Found!

最後まで読んでいただきありがとうございました。
またお会いしましょう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0