๐Ÿ’ป Computer Science/Algorithm

์ด๋ถ„ ํƒ์ƒ‰(Binary Search)

kkh1902 2023. 1. 19. 21:32
728x90
๋ฐ˜์‘ํ˜•

 

์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋œ ๋ฐฐ์—ด์—์„œ ์›ํ•˜๋Š” ์ˆซ์ž(target)์„ ์ฐพ๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์ž…๋‹ˆ๋‹ค.

๋ฐฐ์—ด ์ „์ฒด์˜ ์ค‘๊ฐ„๊ฐ’์„ target ๊ฐ’๊ณผ ๋น„๊ต

์ค‘๊ฐ„๊ฐ’์ด target ๊ฐ’๋ณด๋‹ค ํฌ๋ฉด ์™ผ์ชฝ ๋ถ€๋ถ„๋งŒ ์„ ํƒ

์™ผ์ชฝ๋ถ€๋ถ„์˜ ์ค‘๊ฐ„๊ฐ’์„ ๋‹ค์‹œ target ๊ณผ ๋น„๊ต

์ •๋ฐฉํ–ฅ์œผ๋กœ ํ‘ธ๋Š” ๋ฐฉ๋ฒ•๊ณผ ์žฌ๊ท€๋กœ ํ‘ธ๋Š” ๋ฐฉ๋ฒ• ๋‘ ๊ฐ€์ง€๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.
์ •๋ฐฉํ–ฅ๋„ ์–ด๋–ป๊ฒŒ ๋ณด๋ฉด ๊ฐœ๋…์ ์œผ๋กœ๋Š” ์žฌ๊ท€๋กœ ํ‘ธ๋Š” ๋ฐฉ๋ฒ•๊ณผ ๊ฐ™์€ ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค.

๊ฐœ๋…

  • ์ •๋ ฌ๋œ ์ž๋ฃŒ๋ฅผ ๋ฐ˜์œผ๋กœ ๋‚˜๋ˆ„์–ด ํƒ์ƒ‰ํ•˜๋Š” ๋ฐฉ๋ฒ•
  • ์ฃผ์˜์  : ์ž๋ฃŒ๋Š” ์˜ค๋ฆ„์ฐจ์ˆœ ์œผ๋กœ ์ •๋ ฌ๋œ ์ž๋ฃŒ์—ฌ์•ผ ํ•œ๋‹ค.
  • ์ด์ง„ํŠธ๋ฆฌ, ๋ฐ”์ด๋„ˆ๋ฆฌ์„œ์น˜๋Š” ์ฝ”๋”ฉ ์ธํ„ฐ๋ทฐ ๋‹จ๊ณจ๋ฌธ์ œ
  • ํผํฌ๋จผ์Šค๊ฐ€ ์•„์ฃผ ์ข‹๊ณ  ๊ตฌํ˜„ํ•˜๋Š” ์ค‘์— dynamic programming, recursion์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค.

ํŠน์ง•

  • linear search (์ˆœ์ฐจ๊ฒ€์ƒ‰) : ์ˆœ์„œ๋Œ€๋กœ ์ฐพ๋Š”๋‹ค. ์„ฑ๋Šฅํ‰๊ฐ€์‹œ ๋น„๊ต๋Œ€์ƒ์œผ๋กœ ์‚ฌ์šฉํ•œ๋‹ค.
  • linear search๋Š” ์ •๋ ฌ ๋ฐฉ์‹์ด ์ƒ๊ด€ ์—†๋‹ค.
  • binary search (์ด์ง„ํƒ์ƒ‰) : ๋ฐ˜๋“œ์‹œ ์ •๋ ฌ๋œ ์ƒํƒœ์—์„œ ์‹œ์ž‘ํ•ด์•ผํ•œ๋‹ค. ๋กœ๊ทธ์‹คํ–‰์‹œ๊ฐ„์„ ๋ณด์žฅํ•œ๋‹ค.
  • ์ฐธ๊ณ ๋กœ insert sort (์‚ฝ์ž…์ •๋ ฌ), bubble sort, selection sort๋Š” O(n^2)์˜ ์„ฑ๋Šฅ์„ ๊ฐ–๊ณ  ์žˆ๋‹ค. (์ฐธ๊ณ )

 

์ฒ˜์Œ๋ถ€ํ„ฐ ๋๊นŒ์ง€ ๋Œ๋ฉด์„œ ํƒ์ƒ‰ํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค ํ›จ์”ฌ ๋น ๋ฅธ ์žฅ์ ์„ ์ง€๋‹˜

* ์‹œ๊ฐ„๋ณต์žก๋„
์ „์ฒด ํƒ์ƒ‰ : O(N)
์ด๋ถ„ ํƒ์ƒ‰ : O(logN)

์ง„ํ–‰ ์ˆœ์„œ

  • ์šฐ์„  ์ •๋ ฌ์„ ํ•ด์•ผ ํ•จ
  • left์™€ right๋กœ mid ๊ฐ’ ์„ค์ •
  • mid์™€ ๋‚ด๊ฐ€ ๊ตฌํ•˜๊ณ ์ž ํ•˜๋Š” ๊ฐ’๊ณผ ๋น„๊ต
  • ๊ตฌํ•  ๊ฐ’์ด mid๋ณด๋‹ค ๋†’์œผ๋ฉด : left = mid+1 ๊ตฌํ•  ๊ฐ’์ด mid๋ณด๋‹ค ๋‚ฎ์œผ๋ฉด : right = mid - 1
  • left > right๊ฐ€ ๋  ๋•Œ๊นŒ์ง€ ๊ณ„์† ๋ฐ˜๋ณตํ•˜๊ธฐ

source code

์ •๋ฐฉํ–ฅ

target = 25
m_list = [30, 94, 27, 92, 21, 37, 25, 47, 25, 53, 98, 19, 32, 32, 7]
length = len(m_list)

m_list.sort()
left = 0 
right = length-1

while left<=right:
    mid = (left+right)//2
    if m_list[mid] == target:
        print(mid+1)
        break
    elif m_list[mid]>target:
        right = mid-1
    else :
        left = mid+1

์žฌ๊ท€(Recursive)

def binarySearch(array, target, left, right):
    middle_idx = (left+right)//2
    print(middle_idx)
    middle = array[middle_idx]
    if target == middle:
        print('answer {}'.format(middle_idx))
    elif middle > target:
        binarySearch(array, target,left,middle_idx-1)
    elif middle < target:
        binarySearch(array, target,middle_idx+1,right)
    else: 
        return False

target = 25
m_list = [30, 94, 27, 92, 21, 37, 25, 47, 25, 53, 98, 19, 32, 32, 7]
length = len(m_list)

m_list.sort()
left = 0 
right = length-1

binarySearch(m_list,target,0,right)

 

์ถœ์ฒ˜

https://wayhome25.github.io/cs/2017/04/15/cs-16/ 

https://velog.io/@madfinger/Binary-Search%EC%9D%B4%EC%A7%84-%ED%83%90%EC%83%89-%ED%8C%8C%EC%9D%B4%EC%8D%AC

 

728x90
๋ฐ˜์‘ํ˜•