Algorithm(알고리즘)/재귀함수

6) 리스트 내 요소 찾는 재귀함수

고로케 2021. 5. 13.
반응형

6. 리스트 내 요소 찾는 재귀함수

def binary_search(element, some_list, start_index=0, end_index=None):
    # end_index가 따로 주어지지 않은 경우에는 리스트의 마지막 인덱스
    if end_index == None:
        end_index = len(some_list) - 1

    midpoint = (end_index + start_index) // 2
    if start_index > end_index:
        return None

    if element == some_list[midpoint]:
        return midpoint
    elif element < some_list[midpoint]:
        return binary_search(element, some_list, start_index, midpoint - 1)
    else:
        return binary_search(element, some_list, midpoint + 1, end_index)


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]))

결과 : 0 None 2 1 4




반응형

댓글