Skip to content

Latest commit

ย 

History

History
61 lines (45 loc) ยท 1.74 KB

binary_search.md

File metadata and controls

61 lines (45 loc) ยท 1.74 KB

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

๐Ÿ“Œ ์ด๋ถ„ ํƒ์ƒ‰(Binary Search)

  • ์ด์ง„ ํƒ์ƒ‰ ํ˜น์€ ์ด๋ถ„ ํƒ์ƒ‰์ด๋ผ๊ณ  ๋ถ€๋ฅธ๋‹ค.
  • ์ด๋ฏธ ์ •๋ ฌ๋˜์–ด ์žˆ๋Š” ์ž๋ฃŒ ๊ตฌ์กฐ์—์„œ ํŠน์ • ๊ฐ’์„ ์ฐพ์„ ๋•Œ, ํƒ์ƒ‰ ๋ฒ”์œ„๋ฅผ ์ ˆ๋ฐ˜์”ฉ ๋‚˜๋ˆ ๊ฐ€๋ฉด์„œ ํ•ด๋‹น ๊ฐ’์„ ์ฐพ์•„๊ฐ€๋Š” ๊ฒƒ์ด๋‹ค.
  • ์ฆ‰, ํƒ์ƒ‰ ๋ฒ”์œ„๋ฅผ ๋‘ ๋ถ€๋ถ„์œผ๋กœ ๋ถ„ํ• ํ•˜๋ฉด์„œ ์ฐพ๋Š” ๋ฐฉ์‹์ด๋‹ค.
  • ์ฒ˜์Œ๋ถ€ํ„ฐ ๋๊นŒ์ง€ ๋Œ๋ฉด์„œ ํƒ์ƒ‰ํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค ํ›จ์”ฌ ๋น ๋ฅด๋‹ค๋Š” ์žฅ์ ์„ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค.

์‹œ๊ฐ„ ๋ณต์žก๋„

  • ์ „์ฒด ํƒ์ƒ‰ : O(N)
  • ์ด๋ถ„ ํƒ์ƒ‰ : O(logN)

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

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

[Code]

package Study;

import java.util.Arrays;

/**
 * created by victory_woo on 2020/04/30
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {2, 13, 6, 5, 12, 15, 23, 17, 19, 10,};
        System.out.println(solution(17, arr));
    }

    private static int solution(int target, int[] arr) {
        Arrays.sort(arr);
        int left = 0, right = arr.length - 1, mid = 0;

        while (left < right) {
            mid = (left + right) / 2;

            if (target == arr[mid]) {
                System.out.println("Find Target : " + target + ", Value : " + arr[mid]);
                return arr[mid];
            }

            if (target < arr[mid]) right = mid - 1;
            else left = mid + 1;
        }

        return -1;
    }
}

๊ฒฐ๊ณผ๋ฅผ ์ฐพ์€ ๊ฒฝ์šฐ, ์ฐพ์•˜๋‹ค๋Š” ๋ฉ”์‹œ์ง€์™€ ํ•จ๊ป˜ ์ฐพ์€ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ๊ฒฐ๊ณผ๋ฅผ ์ฐพ์ง€ ๋ชปํ•œ ๊ฒฝ์šฐ์—๋Š” -1์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.