1. 반복문 버전: 디버깅에도 용이하고 메모리도 덜 잡아먹으므로 재귀방식보다 더 추천한다
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static private int[] arr;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
br.close();
}
public static int binarySearch(int key) {
int lowIdx = 0;
int highIdx = arr.length - 1;
while (lowIdx <= highIdx) {
int midIdx = lowIdx + (highIdx - lowIdx) / 2;
if (arr[midIdx] < key) {
lowIdx = midIdx + 1;
} else if (arr[midIdx] > key) {
highIdx = midIdx - 1;
} else {
return midIdx;
}
}
return -1;
}
}
2. 재귀 버전: 디버깅에 용이하지 않고 메모리(스택 메모리)를 더 사용하게 되므로 추천하지는 않는다
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static private int[] arr;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
br.close();
}
public static int binarySearch(int key, int lowIdx, int highIdx) {
if (lowIdx > highIdx) {
return -1;
}
int midIdx = lowIdx + (highIdx - lowIdx) / 2;
if (arr[midIdx] < key) {
return binarySearch(key, midIdx + 1, highIdx);
} else if (arr[midIdx] > key) {
return binarySearch(key, lowIdx, midIdx - 1);
} else {
return midIdx;
}
}
}
'problem solving > java' 카테고리의 다른 글
PriorityQueue() 사용법 (1) | 2024.10.27 |
---|