์•Œ๊ณ ๋ฆฌ์ฆ˜

[Algorithm] ์ด์ง„ ํƒ์ƒ‰ (Binary Search)

jjingle 2024. 2. 6. 17:02

์ด์ง„ ํƒ์ƒ‰ (Binary Search) ?

ํƒ์ƒ‰ํ•  ์ž๋ฃŒ๋ฅผ ๋‘˜๋กœ ๋‚˜๋ˆ„์–ด ํ•ด๋‹น ๋ฐ์ดํ„ฐ๊ฐ€ ์žˆ์„๋งŒํ•œ ๊ณณ์„ ํƒ์ƒ‰ํ•˜๋Š” ๋ฐฉ๋ฒ•

 

 

๋ถ„ํ•  ์ •๋ณต ์•Œ๊ณ ๋ฆฌ์ฆ˜๊ณผ ์ด์ง„ ํƒ์ƒ‰

  • ๋ถ„ํ•  ์ •๋ณต ์•Œ๊ณ ๋ฆฌ์ฆ˜ (Divide and Conquer)
    • Divide : ๋ฌธ์ œ๋ฅผ ํ•˜๋‚˜ ๋˜๋Š” ๋‘˜ ์ด์ƒ์œผ๋กœ ๋‚˜๋ˆˆ๋‹ค.
    • Conquer :  ๋‚˜๋ˆ ์ง„ ๋ฌธ์ œ๊ฐ€ ์ถฉ๋ถ„ํžˆ ์ž‘๊ณ , ํ•ด๊ฒฐ์ด ๊ฐ€๋Šฅํ•˜๋ฉด ํ•ด๊ฒฐํ•˜๊ณ , ๊ทธ๋ ‡์ง€ ์•Š๋‹ค๋ฉด ๋‹ค์‹œ ๋‚˜๋ˆˆ๋‹ค.
  • ์ด์ง„ ํƒ์ƒ‰ 
    • Divide : ๋ฆฌ์ŠคํŠธ๋ฅผ ๋‘ ๊ฐœ์˜ ์„œ๋ธŒ ๋ฆฌ์ŠคํŠธ๋กœ ๋‚˜๋ˆˆ๋‹ค.
    • Conquer
      • ๊ฒ€์ƒ‰ํ•  ์ˆซ์ž(search) > ์ค‘๊ฐ„๊ฐ’ , ๋’ท ๋ถ€๋ถ„์˜ ์„œ๋ธŒ ๋ฆฌ์ŠคํŠธ์—์„œ ๊ฒ€์ƒ‰ํ•  ์ˆซ์ž๋ฅผ ์ฐพ๋Š”๋‹ค.
      • ๊ฒ€์ƒ‰ํ•  ์ˆซ์ž(search) < ์ค‘๊ฐ„๊ฐ’ , ์•ž ๋ถ€๋ถ„์˜ ์„œ๋ธŒ ๋ฆฌ์ŠคํŠธ์—์„œ ๊ฒ€์ƒ‰ํ•  ์ˆซ์ž๋ฅผ ์ฐพ๋Š”๋‹ค.
def binary_search(data, search):
  if len(data) == 1 and search == data[0]:
    return True
  if len(data) == 1 and search != data[0]:
    return False
  if len(data) == 0:
    return False
    
  medium = len(data) // 2
  
  if search == data[medium]:
    return True
  else:
    if search > data[medium]:
      return binary_search(data[medium + 1:], search)
    else:
      return binary_search(data[:medium], search)