Created
April 11, 2020 08:41
-
-
Save lockdef/d84bb4a18cb9560787abbcd70eb66121 to your computer and use it in GitHub Desktop.
二分探索(めぐみ式)です
This file contains 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
# 参考 : https://qiita.com/drken/items/97e37dd6143e33a64c8c | |
a = [1, 14, 32, 51, 51, 51, 243, 419, 750, 910] | |
def binary_search(key, list_): | |
def isOK(index, key): | |
if a[index] >= key: | |
return True | |
return False | |
ng = -1 | |
ok = len(list_) | |
while abs(ok - ng) > 1: | |
mid = (ok + ng) // 2 | |
if isOK(mid, key): | |
ok = mid | |
else: | |
ng = mid | |
return ok | |
if __name__ == "__main__": | |
print(binary_search(51, a)) # Output : 3 | |
print(binary_search(1, a)) # Output : 0 | |
print(binary_search(52, a)) # Output : 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment