binary_search

์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ ์ƒ๋‹นํžˆ ์ค€๋‹ค.

์ตœ์ ํ™” ๋ฌธ์ œ๋ฅผ ๊ฒฐ์ •๋ฌธ์ œ ( ์˜ˆ ํ˜น์€ ์•„๋‹ˆ์˜ค ๋กœ ๋‹ตํ•˜๋Š” ๋ฌธ์ œ ) ๋กœ ๋ฐ”๊พธ์–ด ํ•ด๊ฒฐํ•˜๋Š” ํŒŒ๋ผ๋ฉ”ํŠธ๋ฆญ ์„œ์น˜์œ ํ˜•์€ ์ด์ง„ํƒ์ƒ‰์„ ์ด์šฉํ•˜์—ฌ ํ•ด๊ฒฐ ๊ฐ€๋Šฅ ์ฃผ์–ด์ง„ ์ˆ˜๊ฐ€ ํฐ ์ˆ˜๋ผ๋ฉด ๊ฐ€์žฅ ๋จผ์ € ์ด์ง„ํƒ์ƒ‰์„ ๋– ์˜ฌ๋ฆฌ์ž

Mid ( ์ค‘๊ฐ„์  ) ์ด ํ•ต์‹ฌ

์ข…๋ฃŒ์กฐ๊ฑด์€ Start > end ์ผ ๋•Œ ! ๋” ์ด์ƒ ์ด์ง„ํƒ์ƒ‰์€ ์˜๋ฏธ๊ฐ€ ์—†์Œ

์žฌ๊ท€

def binary_search(array, target, start, end):
    if start > end: # ์ด๊ฒƒ๋„ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ์žฌ๊ท€์ด๊ธฐ ๋•Œ๋ฌธ์—, ์žฌ๊ท€ํ•ด์„œ ๋“ค์–ด์˜จ ๊ฒƒ์„ ๊ณ ๋ คํ•˜์—ฌ ์ฒ˜์Œ ์กฐ๊ฑด์„ ์„ค์ •ํ•ด์ค˜์•ผ ํ•œ๋‹ค.
        return None
    mid = (start + end) //2 # ์ค‘๊ฐ„์ ์˜ ์ธ๋ฑ์Šค

    if array[mid] == target: # ์ฐพ์€ ๊ฒฝ์šฐ ์ธ๋ฑ์Šค ๋ฐ˜ํ™˜
        return mid

    elif array[mid] > target: # ์ฐพ๊ณ ์ž ํ•˜๋Š” ๊ฐ‘์ด ์ค‘๊ฐ„๋ณด๋‹ค ์ž‘์€ ๊ฒฝ์šฐ, ์ค‘๊ฐ„์ ์˜ ์™ผ์ชฝ ํ™•์ธ
        return binary_search(array,target,start,mid-1)

    else:
        return binary_search(array,target,mid+1,end)


n, target = list(map(int,input().split()))
array = list(map(int,input().split()))

rst = binary_search(array,target,0,n-1)

if rst == None:
    print('์›์†Œ๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.')

else:
    print(rst + 1)

๋ฐ˜๋ณต๋ฌธ

def binary_search(array,target,start,end):
    while start <= end:
        mid = (start + end) // 2

        if array[mid] == target:
            return mid

        elif array[mid] > target:
            end = mid -1

        else:
            start = mid + 1

    return None

n, target = list(map(int,input().split()))

array = list(map(int,input().split()))

rst = binary_search(array,target,0,n-1)

if rst == None:
    print('์›์†Œ๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.')

else:
    print(rst + 1)

Last updated