Quick actions

cmd+k|ctrl+k

Navigation

Languages

binary search

Snippet info

Language

Cpp

Visibility

public

Author

creditfool

Created

2021-10-26T08:31:54.669041Z

Updated

2021-10-26T15:00:46.732968Z

// Ichlalsul Bulqiah
// 190535646047

#include <iostream>
using namespace std;

int binarySearch(int *arr, int target, int topIdx, int bottomIdx = 0) {
    
    if (bottomIdx <= topIdx && target >= arr[bottomIdx] && target <= arr[topIdx]) {
        int mid = (topIdx+bottomIdx) / 2;
        
        if (arr[mid] == target) {
            return mid;
        } 
        else if (arr[mid] < target) {
            return binarySearch(arr, target, topIdx, mid+1);
        }
        else if (arr[mid] > target) {
            return binarySearch(arr, target, mid-1, bottomIdx);
        }
    }
    else {
        return -1;
    }
}


int main() {
    int foo[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int searchTarget = 7;
    
    int arrLength = sizeof(foo)/sizeof(foo[0])-1;
    int bar = binarySearch(foo, searchTarget, arrLength);
    
    cout << bar << endl;
    
    return 0;
}
INFO