binary search

Run Settings
LanguageC++
Language Version
Run Command
// 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; }
Editor Settings
Theme
Key bindings
Full width
Lines