본문 바로가기
알고리즘 문제 풀이

직접 구현해본 이분탐색 upperbound와 lowerbound

by 가나무마 2022. 1. 30.
728x90
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int[] array = new int[100];
        for (int i = 0; i < array.length; i++) {
            array[i] = (int)(Math.random()*30);
        }
        Arrays.sort(array);

        while (true) {
            System.out.println("찾으시는 번호를 입력해주세요.");
            int target = Integer.parseInt(br.readLine());
            int lowerBound = lowerBound(array,target);
            System.out.println("lowerBound : "+lowerBound+" array[lowerBound] : "+array[lowerBound]);
            int upperBound = upperBound(array,target);
            System.out.println("upperBound : "+upperBound+" array[upperBound] : "+array[upperBound]);
            System.out.println(Arrays.toString(array));
        }
    }
    
    private static int lowerBound(int[] array, int target) {
        int left = 0;
        int right = array.length-1;

        while (left <= right) {
            int mid = left+(right-left)/2;
            if (array[mid] < target) {
                left = mid+1;
            } else if (array[mid] >= target) {
                right = mid-1;
            }
        }

        return left;
    }
    
    private static int upperBound(int[] array, int target) {
        int left = 0;
        int right = array.length-1;
        while (left <= right) {
            int mid = left+(right-left)/2;
            if (array[mid] <= target) {
                left = mid+1;
            } else if (array[mid] > target) {
                right = mid-1;
            }
        }

        return left;
    }
}
728x90
반응형