728x90
반응형
Binary Search (이진탐색)
- 데이터 집합의 중앙값을 확인
- 중앙값이 찾는 값과 같다면 search 종료
- 찾는 값이 중앙값 보다 크다면, 중앙값의 오른쪽 부분에서 search
- 찾는 값이 중앙값보다 작다면, 중앙갑의 왼쪽 부분에서 search
- 반복
탐색 시간: log n
단점: 정렬되어 있는 데이터에만 사용 가능
public class BinarySearch {
int binarySearch(int arr[], int target) {
int low = 0, high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
public static void main(String[] args) {
BinarySearch bs = new BinarySearch();
int arr[] = {2, 3, 4, 10, 40};
int target = 10;
int result = bs.binarySearch(arr, target);
if (result == -1)
System.out.println("없음");
else
System.out.println("해당 값의 인덱스: " + result);
}
}
728x90
반응형
'전공 > 자료구조와 실습' 카테고리의 다른 글
Queue) Circular Queue (0) | 2024.01.03 |
---|---|
Queue) Queue란? (0) | 2024.01.03 |
Set) Hash set (2) | 2024.01.02 |
Map) HashMap (1) | 2024.01.02 |
C++) Bubble Sort (버블 정렬), Selection Sort (선택 정렬), Insertion Sort (삽입 정렬) (0) | 2023.08.04 |