[Algorithm] ์ด์ง„ ํƒ์ƒ‰ | Binary Search
๐Ÿ–ฅ CS/Algorithm

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

 

1. ์ˆœ์ฐจ ํƒ์ƒ‰

 

: ๊ฐ€์žฅ ๊ธฐ๋ณธ์ ์ธ ํƒ์ƒ‰ ๋ฐฉ๋ฒ•

 

- ๋ฆฌ์ŠคํŠธ ์•ˆ์— ์žˆ๋Š” ํŠน์ • ๋ฐ์ดํ„ฐ๋ฅผ ์ฐพ๊ธฐ ์œ„ํ•ด ์•ž์—์„œ๋ถ€ํ„ฐ ํ•˜๋‚˜์”ฉ ํ™•์ธ

- ์ •๋ ฌ๋˜์ง€ ์•Š์€ ๋ฆฌ์ŠคํŠธ์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ์ฐพ์„ ๋•Œ ์‚ฌ์šฉ

- ํŒŒ์ด์ฌ์˜ count() ๋ฉ”์„œ๋“œ ๋‚ด๋ถ€์—์„œ ์ˆœ์ฐจ ํƒ์ƒ‰์ด ์‚ฌ์šฉ๋œ๋‹ค.

 

๐Ÿ“Œ ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)

 

# target = ์ฐพ๊ณ ์žํ•˜๋Š” ์›์†Œ
def search(n, target, array):
	for i in range(n):
    	# ํ˜„์žฌ์˜ ์›์†Œ๊ฐ€ target๊ณผ ๋™์ผํ•˜๋ฉด
    	if array[i] == target:
        		return i # ํ˜„์žฌ์˜ ์œ„์น˜ ์ธ๋ฑ์Šค ๋ฐ˜ํ™˜

 

 

2. ์ด์ง„ ํƒ์ƒ‰(์ด๋ถ„ ํƒ์ƒ‰)

 

: ๋ฒ”์œ„๋ฅผ ์ ˆ๋ฐ˜์”ฉ ๋‚˜๋ˆ„๋ฉฐ ํƒ์ƒ‰ํ•˜๋Š” ๋ฐฉ๋ฒ•

 

- ๋ฐฐ์—ด ๋‚ด๋ถ€ ๋ฐ์ดํ„ฐ๊ฐ€ ์ •๋ ฌ๋˜์–ด ์žˆ์–ด์•ผ ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅ

- ๋ณ€์ˆ˜ 3๊ฐœ ํ•„์š”: ์‹œ์ž‘์ , ๋์ , ์ค‘๊ฐ„์ 

- ์ค‘๊ฐ„์ ์ด ์‹ค์ˆ˜ ์ผ ๋•Œ๋Š” ์†Œ์ˆ˜์  ์ดํ•˜๋ฅผ ๋ฒ„๋ฆฐ๋‹ค.

- ์ฐพ์œผ๋ ค๋Š” ๋ฐ์ดํ„ฐ์™€ ์ค‘๊ฐ„์  ์œ„์น˜์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๋น„๊ตํ•˜๋ฉฐ ํƒ์ƒ‰

๐Ÿ“Œ ์‹œ๊ฐ„ ๋ณต์žก๋„: O(logN) ๋ณด์žฅ

 

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

 

๐Ÿ“Œ ํŒŒ์ด์ฌ ๋‚ด๋ถ€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ bisect

 

- bisect_left(a,x): ์ •๋ ฌ๋œ ์ˆœ์„œ๋ฅผ ์œ ์ง€ํ•˜๋ฉด์„œ ๋ฐฐ์—ด a์— x๋ฅผ ์‚ฝ์ž…ํ•  ๊ฐ€์žฅ ์™ผ์ชฝ ์ธ๋ฑ์Šค ๋ฐ˜ํ™˜

- bisect_right(a,x): ์ •๋ ฌ๋œ ์ˆœ์„œ๋ฅผ ์œ ์ง€ํ•˜๋ฉด์„œ ๋ฐฐ์—ด a์— x๋ฅผ ์‚ฝ์ž…ํ•  ๊ฐ€์žฅ ์˜ค๋ฅธ์ชฝ ์ธ๋ฑ์Šค ๋ฐ˜ํ™˜

 

from bisect import bisect_left,bisect_right

a = [1,3,4,5,5,6,6]
x = 4

print(bisect_left(a,x)) # 3
print(bisect_right(a,x)) # 5