Last active
June 4, 2019 17:48
-
-
Save srishanbhattarai/1ebec25dc5a6af96c32c064f2d67ae23 to your computer and use it in GitHub Desktop.
Binary Search C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| using namespace std; | |
| int binarySearch(int array[], int size, int searchValue) { | |
| int lo = 0, hi = size - 1; | |
| int mid; | |
| while (hi > lo) { | |
| mid = (lo + hi) / 2; | |
| if (searchValue == array[mid]) { | |
| return mid; | |
| } | |
| if (searchValue > array[mid]) { | |
| lo = mid + 1; | |
| } else { | |
| hi = mid - 1; | |
| } | |
| } | |
| return -1; | |
| } | |
| void binarySearchAndPrint(int array[], int size, int searchValue) { | |
| int foundIndex = binarySearch(array, size, searchValue); | |
| if (foundIndex == -1) { | |
| cout << searchValue << ": not found" << endl; | |
| } else { | |
| cout << searchValue << " found at index: " << foundIndex << endl; | |
| } | |
| } | |
| int main() { | |
| int array[] = {12, 22, 34, 47, 55, 67, 82, 98}; | |
| int size = sizeof(array) / sizeof(int); | |
| binarySearchAndPrint(array, size, 82); | |
| binarySearchAndPrint(array, size, 22); | |
| binarySearchAndPrint(array, size, 10); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment