๐Ÿ’ป

[์•Œ๊ณ ๋ฆฌ์ฆ˜] ์ด๋ถ„ ํƒ์ƒ‰(์ด์ง„ํƒ์ƒ‰) - BinarySearch ๋ณธ๋ฌธ

์•Œ๊ณ ๋ฆฌ์ฆ˜/๊ธฐ๋ณธ๊ธฐ ๋‹ค์ง€๊ธฐ

[์•Œ๊ณ ๋ฆฌ์ฆ˜] ์ด๋ถ„ ํƒ์ƒ‰(์ด์ง„ํƒ์ƒ‰) - BinarySearch

๋˜ํšจ๋‹ˆ 2020. 2. 5. 18:15

์ด๋ถ„ ํƒ์ƒ‰(์ด์ง„ํƒ์ƒ‰) ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์€ ์ฐพ์„ ๋ฒ”์œ„๋ฅผ ๋ฐ˜์œผ๋กœ ๋‚˜๋ˆ ์„œ ํƒ์ƒ‰ํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด๋‹ค.

์ฒ˜์Œ ์ค‘๊ฐ„์˜ ๊ฐ’์„ ์ž„์˜์˜ ๊ฐ’์œผ๋กœ ์„ ํƒํ•˜์—ฌ, ๊ทธ ๊ฐ’๊ณผ ํ‚ค๊ฐ’์˜ ํฌ๊ณ  ์ž‘์Œ์„ ๋น„๊ตํ•˜๋Š” ๋ฐฉ์‹์ด๋‹ค. ์ฒ˜์Œ ์„ ํƒํ•œ ์ค‘๊ฐ„๊ฐ’์ด ๋งŒ์•ฝ ์ฐพ๋Š” ๊ฐ’๋ณด๋‹ค ํฌ๋ฉด ์ตœ๋Œ“๊ฐ’์ด ๋˜๊ณ , ์ž‘์œผ๋ฉด ์ตœ์†Ÿ๊ฐ’์ด ๋œ๋‹ค.

 

- ๋ถ„ํ•  ์ •๋ณต ์•Œ๊ณ ๋ฆฌ์ฆ˜์— ์†ํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด๋‹ค. 

- ๋‹จ, ์ด๋ฏธ ์ •๋ ฌ๋œ ๊ฒฝ์šฐ์—๋งŒ ์ ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

- ์ตœ์•…์˜ ๊ฒฝ์šฐ๋Š” ์ฐพ์œผ๋ ค๋Š” ํ‚ค๊ฐ’์ด ๋ฐฐ์—ด์— ์กด์žฌํ•˜์ง€ ์•Š์„ ๋•Œ์ด๋‹ค.

- ์‹œ๊ฐ„๋ณต์žก๋„๋Š” O(logN) ์ด๋‹ค.

 

 

๋ฐ˜๋ณต๋ฌธ์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ

int BinarySearch(int arr[], int length, int key){
	int first = 0;
    	int last = length - 1;
    	int mid = 0;
    
        while(first <= last){
            mid = (first+last)/2;
            if(arr[mid] > key){ // ์ค‘๊ฐ„๊ฐ’์ด ์ฐพ์œผ๋ ค๋Š” ํ‚ค๊ฐ’๋ณด๋‹ค ํฌ๋‹ค๋ฉด
                last = mid - 1;
            }else if(arr[mid] < key){ // ์ค‘๊ฐ„๊ฐ’์ด ์ฐพ์œผ๋ ค๋Š” ํ‚ค๊ฐ’๋ณด๋‹ค ์ž‘๋‹ค๋ฉด
                low = mid + 1;
            }else{ // ์ค‘๊ฐ„๊ฐ’๊ณผ ์ฐพ์œผ๋ ค๋Š” ํ‚ค๊ฐ’์ด ๊ฐ™๋‹ค๋ฉด
                return mid;
            }
        }
        return -1; // ํ‚ค๊ฐ’์„ ๋ชป์ฐพ์œผ๋ฉด -1์„ ๋ฆฌํ„ด
}

 

์žฌ๊ท€ํ˜ธ์ถœ์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ

int BinarySearch(int arr[], int key, int first, int last){
      int mid = 0;

      if(first>last){
          return -1;
      }else{
          mid = (first+last)/2;
          if(arr[mid] == key){
              return mid;
          }else if(arr[mid] < key){
              BinarySearch(arr, key, first, mid-1);
          }else{
              BinarySearch(arr, key, mid+1, last);
          }
      }
}
๋ฐ˜์‘ํ˜•
Comments