Advertisement
CHU2

Iterative Binary Search 2.0

Mar 24th, 2023
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | Source Code | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int binarySearch(int array[], const int, int);
  6.  
  7. int main() {
  8.     const int size = 5;
  9.     int array[size] = { 2, 3, 4, 10, 40 };
  10.     int search = 10;
  11.  
  12.     int result = binarySearch(array, size, search);
  13.  
  14.     if (result != NULL) {
  15.         cout << "Element " << search << " present at index " << result;
  16.     }
  17.     else {
  18.         cout << "Element " << search << " is not present in array";
  19.     }
  20.  
  21.     return 0;
  22. }
  23.  
  24. int binarySearch(int array[], const int size, int search) {
  25.     int low = 0;
  26.     int high = size - 1;
  27.     int mid;
  28.  
  29.     while (low <= high) {
  30.         mid = low + (high -1) /2;
  31.  
  32.         if (array[mid] == search) {
  33.             return mid;
  34.         }
  35.         if (array[mid] < search) {
  36.             low = mid + 1;
  37.         }
  38.         else {
  39.             high = mid - 1;
  40.         }
  41.     }
  42.     return NULL;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement