목록이 정렬되면 이진 검색 기술을 사용하여 목록에서 항목을 찾을 수 있습니다. 이 절차에서 전체 목록은 두 개의 하위 목록으로 나뉩니다. 항목이 중간 위치에 있으면 위치를 반환하고, 그렇지 않으면 왼쪽 또는 오른쪽 하위 목록으로 점프하여 항목을 찾거나 범위를 초과할 때까지 동일한 과정을 다시 수행합니다.
이진 검색 기법의 복잡성
- 시간 복잡성 : O(1)은 최상의 경우입니다. 평균 또는 최악의 경우 O(log2 n).
- 공간 복잡성: O(1)
입력 및 출력
Input: A sorted list of data: 12 25 48 52 67 79 88 93 The search key 79 Output: Item found at location: 5
알고리즘
binarySearch(array, start, end, key)
입력 - 정렬된 배열, 시작 및 종료 위치, 검색 키
출력 - 키의 위치(발견된 경우), 그렇지 않으면 잘못된 위치입니다.
Begin if start <= end then mid := start + (end - start) /2 if array[mid] = key then return mid location if array[mid] > key then call binarySearch(array, mid+1, end, key) else when array[mid] < key then call binarySearch(array, start, mid-1, key) else return invalid location End
예시
#include<iostream>
using namespace std;
int binarySearch(int array[], int start, int end, int key) {
if(start <= end) {
int mid = (start + (end - start) /2); //mid location of the list
if(array[mid] == key)
return mid;
if(array[mid] > key)
return binarySearch(array, start, mid-1, key);
return binarySearch(array, mid+1, end, key);
}
return -1;
}
int main() {
int n, searchKey, loc;
cout << "Enter number of items: ";
cin >> n;
int arr[n]; //create an array of size n
cout << "Enter items: " << endl;
for(int i = 0; i< n; i++) {
cin >> arr[i];
}
cout << "Enter search key to search in the list: ";
cin >> searchKey;
if((loc = binarySearch(arr, 0, n, searchKey)) >= 0)
cout << "Item found at location: " << loc << endl;
else
cout << "Item is not found in the list." << endl;
} 출력
Enter number of items: 8 Enter items: 12 25 48 52 67 79 88 93 Enter search key to search in the list: 79 Item found at location: 5