Created
May 15, 2021 17:07
-
-
Save Park-Developer/66be9510609221bd101652cd4e1936bf to your computer and use it in GitHub Desktop.
binary_search
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
from typing import Any, Sequence | |
def bin_search(a : Sequence, key : Any)-> int: | |
'''시퀀스 a에서 key와 일치하는 원소를 이진 검색''' | |
pl =0 | |
pr= len(a)-1 | |
while True: | |
pc=(pl+pr)//2 # 중앙 우너소의 인덱스 | |
if a[pc]==key: | |
return pc | |
elif a[pc]<key: # 검색 범위를 뒤쪽 절반으로 좁힘 | |
pl=pc+1 | |
elif a[pc]>key: # 검색 범위를 앞쪽 절반으로 좁힘 | |
pr=pc-1 | |
if pl>pr: | |
break | |
return -1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment