Skip to content

Instantly share code, notes, and snippets.

@DongguemYoo
Created June 23, 2020 12:58
Show Gist options
  • Save DongguemYoo/a16985d56348bc8037910127adc679a1 to your computer and use it in GitHub Desktop.
Save DongguemYoo/a16985d56348bc8037910127adc679a1 to your computer and use it in GitHub Desktop.
[codeit] 이진탐색알고리즘 python
def binary_search(element, some_list):
answer = None
startIdx=0
endIdx=len(some_list) - 1
if element < some_list[0] or element > some_list[len(some_list) - 1]:
return None
while answer == None:
if some_list[startIdx] == element:
answer = startIdx
break
elif some_list[endIdx] == element:
answer = endIdx
break
middleIndex = int((endIdx + startIdx) / 2)
if element > some_list[middleIndex]:
startIdx =middleIndex + 1
# search(some_list, middleIndex + 1, endIndex, targetValue)
elif element < some_list[middleIndex]:
endIdx =middleIndex-1
# search(some_list, startIndex, middleIndex - 1, targetValue)
else:
return middleIndex
return answer
# 코드를 작성하세요.
# print(binary_search(2, [2, 3, 5, 7, 11]))
# print(binary_search(0, [2, 3, 5, 7, 11]))
# print(binary_search(5, [2, 3, 5, 7, 11]))
print(binary_search(3, [2, 3, 5, 7, 11]))
# print(binary_search(11, [2, 3, 5, 7, 11]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment