Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- int binarySearch(int array[], const int, int);
- int main() {
- const int size = 5;
- int array[size] = { 2, 3, 4, 10, 40 };
- int search = 10;
- int result = binarySearch(array, size, search);
- if (result != NULL) {
- cout << "Element " << search << " present at index " << result;
- }
- else {
- cout << "Element " << search << " is not present in array";
- }
- return 0;
- }
- int binarySearch(int array[], const int size, int search) {
- int low = 0;
- int high = size - 1;
- int mid;
- while (low <= high) {
- mid = low + (high -1) /2;
- if (array[mid] == search) {
- return mid;
- }
- if (array[mid] < search) {
- low = mid + 1;
- }
- else {
- high = mid - 1;
- }
- }
- return NULL;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement