Binary Search (easy)

JUNE 10, 2023

문제

  • 이진검색

007 01

  • 주어진 코드
public class Solution {
    public static void main(String[] args) {
        System.out.println(search(new int[]{-1,0,3,5,9,12}, 9)); // 4
        System.out.println(search(new int[]{-1,0,3,5,9,12}, 2)); // -1
        System.out.println(search(new int[]{2,5}, 2)); // 0
        System.out.println(search(new int[]{5}, 5)); // 0

    }
    public static int search(int[] nums, int target) {
        //
    }
}

결과 및 풀이

  • 결과

007 02

  • 풀이
public static int search(int[] nums, int target) {
    int endIndex = nums.length - 1;
    int startIndex = 0;
    int mid;
    
    while (startIndex <= endIndex) {
        mid = (endIndex + startIndex) / 2;
        
        if(target == nums[mid]) {
            return mid;
        } else if (target > nums[mid]) {
            startIndex = mid + 1;
        } else {
            endIndex = mid - 1;
        }
    }
    
    return -1;
}

배웠다

  • 중간값을 구하는 식은 (startIndex+endIndex)/2
  • 이건 좀 외우자.. 잘 못풀어서 충격이다…

작업 기록 블로그