Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

두's 스토리

이진검색 본문

알고리즘

이진검색

알 수 없는 사용자 2019. 7. 22. 21:48

이진검색(Binary Search)

자료의 가운데부터 검색하고 가운데 값보다 값이 작으면 왼쪽으로 크면 오른쪽으로 탐색

이진검색을 하기 위해서는 자료가 정렬된 상태이어야 함

<재귀로 구현>

#include <iostream>
using namespace std;

int target = 7;
int f(int* arr, int front, int end);
int main(){
    int arr[] = { 2, 4, 7, 9, 11, 19, 23 };
    int n = sizeof(arr) / sizeof(int);
    int ans = f(arr, 0, n - 1);
    if (ans != -1){
        cout << ans;
    }
    else
        cout << "no find";
}
int f(int* arr, int front, int end){
    int mid = (front + end) / 2;
    if (front > end){
        return -1;
    }
    if (arr[mid] == target){
        return mid;
    }
    else if (target < arr[mid]){
        return f(arr, front, mid - 1);
    }
    else{
        return f(arr, mid + 1, end);
    }
}

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

다익스트라  (0) 2019.08.01
Knapsack  (0) 2019.07.30
순열 & 조합  (0) 2019.07.26