본문 바로가기

알고리즘/Algorithm

2진검색 알고리즘

반응형

데이터가 크기순으로 배열에 저장되어 있다고 가정.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static int binarySearch(String[] items, String target, int begin, int end) {
        if(begin > end)
            return -1;
        else {
            int middle = (begin+end)/2;
            int compResult = target.compareTo(items[middle]); //target이 크면 1 작으면 -1 같으면 0
            if(compResult == 0)
                return middle;
            else if (compResult<0)
                return binarySearch(items, target, begin, middle-1);
            else
                return binarySearch(items, target, middle+1, end);
        }
    }
cs
반응형

'알고리즘 > Algorithm' 카테고리의 다른 글

Dynamic Programing 피보나치  (0) 2022.01.04
Recursion의 응용 - 미로찾기  (0) 2021.01.19
Recursion(순환)-3  (0) 2021.01.19
Recursion(순환)-2  (0) 2020.07.05
선형 시간 알고리즘  (0) 2020.07.05