Krononberg

binary search (C++) 본문

개발 로그/자료구조

binary search (C++)

k._. 2024. 2. 9. 06:49
#include<iostream>

using namespace std;



int binary_search(int arr[], int size, int target){
    int left = 0;
    int right = size - 1;
    while (left <= right){
        int mid = (left + right) / 2;

        if (arr[mid] == target)
            return mid;

        if (arr[mid] < target)
            left = mid + 1;
        else
            right = mid - 1;
    }
    return -1;
}


int main(){
    int arr[] = {1,3,5,6,7,9,11,14,16,17,10,33};
    int target = 14;

    int size = sizeof(arr) / sizeof(arr[0]);

    int result = binary_search(arr, size, target);
    
    cout << result;

    return 0;
}

'개발 로그 > 자료구조' 카테고리의 다른 글

quick sort (C++)  (0) 2024.02.09
bfs graph (C++)  (0) 2024.02.09