๐ŸŒป JAVA/์•Œ๊ณ ๋ฆฌ์ฆ˜, ์ž๋ฃŒ๊ตฌ์กฐ

์•Œ๊ณ ๋ฆฌ์ฆ˜ - ์ด๋ถ„ ํƒ์ƒ‰ (Binary Search)

iseunghan 2021. 11. 25. 21:49
๋ฐ˜์‘ํ˜•

์•ˆ๋…•ํ•˜์„ธ์š”, ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ •๋ฆฌํ•˜๋Š” ํฌ์ŠคํŒ…์ž…๋‹ˆ๋‹ค. ๋‹ค๋ฅธ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ฐธ๊ณ ํ•˜์‹œ๋ ค๋ฉด ํ•ด๋‹น ์นดํ…Œ๊ณ ๋ฆฌ๋ฅผ ์ด์šฉํ•ด์ฃผ์„ธ์š”. ๐Ÿ˜Š

 

'๐ŸŒป JAVA/์•Œ๊ณ ๋ฆฌ์ฆ˜, ์ž๋ฃŒ๊ตฌ์กฐ' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๊ธ€ ๋ชฉ๋ก

๊ณต๋ถ€ํ•œ ๊ฒƒ๋“ค ์ •๋ฆฌํ•œ ๋‚ด์šฉ์„ ํฌ์ŠคํŒ…ํ•ฉ๋‹ˆ๋‹ค.

iseunghan.tistory.com

 

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

์ด๋ถ„ ํƒ์ƒ‰์€ ํƒ์ƒ‰ ๋ฒ”์œ„๋ฅผ ๋‘๊ฐœ๋กœ ๋‚˜๋ˆ ์„œ ํƒ์ƒ‰ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ํ›จ์”ฌ ๋น ๋ฅธ ํƒ์ƒ‰ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ž…๋‹ˆ๋‹ค.

 

์ฒ˜์Œ๋ถ€ํ„ฐ ์ฐจ๋ก€๋Œ€๋กœ ํƒ์ƒ‰ : O(N)
์‹œ๊ฐ„ ๋ณต์žก๋„ : O(log N)

 

 

๊ณผ์ •

0. ํƒ์ƒ‰ํ•˜๊ธฐ ์œ„ํ•œ ๋ฐฐ์—ด, ์ฐพ๊ณ ์ž ํ•˜๋Š” ๊ฐ’ : 9 (์ดํ•˜ Target)

 

1. ๋จผ์ € ๋ฐฐ์—ด์„ ์ •๋ ฌ์‹œํ‚ต๋‹ˆ๋‹ค.

 

2. ์ธ๋ฑ์Šค L, R, MID๋ฅผ ์ง€์ •ํ•ด์ค๋‹ˆ๋‹ค.

 

3.  if (Target == arr[M])

if(target == arr[M]) {
	return M;
}

 

4. else if (Target > arr[M])

M ์ดํ•˜์˜ ์ˆ˜๋“ค์€ ๋ฒ”์œ„์—์„œ ์ œ์™ธํ•ฉ๋‹ˆ๋‹ค.

 

5. else if (Target < arr[M])

M ์ด์ƒ์˜ ์ˆ˜๋“ค์€ ๋ฒ”์œ„์—์„œ ์ œ์™ธํ•ฉ๋‹ˆ๋‹ค.

 

6. ๋‹ค์‹œ 2๋ฒˆ ๊ณผ์ •์œผ๋กœ ๋Œ์•„๊ฐ‘๋‹ˆ๋‹ค.

 

์ „์ฒด ์ฝ”๋“œ (Code)

public int binary_Search(int[] arr, int target) {

    // ์ •๋ ฌ์ด ์•ˆ๋˜์–ด์žˆ๋‹ค๋ฉด, ์ •๋ ฌ ๋จผ์ €!
    Arrays.sort(arr);
    
    int L = 0, R = arr.length-1, M = 0;
    
    while(L != R) {
    	M = (L + R) / 2;
        
        if(target == arr[M])	return M;
        else if(target > arr[M]) {
        	L = M + 1;
        } else {	// target < arr[M]
        	R = M - 1;
        }
    }
    return -1;
}
๋ฐ˜์‘ํ˜•