avr39ripe

cppBinSearchExample

Jul 21st, 2021
911
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <chrono>
  3.  
  4. int main()
  5. {
  6.     const int arrSize{ 10 };
  7.    
  8.     int key{ -1 };
  9.  
  10.     bool found{ false };
  11.  
  12.     //int arr[arrSize]{ 6,1,4,2,8,9,11,3,2,13 };
  13.     int arr[arrSize]{ -1,1,2,2,4,6,8,9,11,13 };
  14.     int left{ 0 };
  15.     int right{ arrSize - 1 };
  16.     int mid{};
  17.  
  18.     while ( left <= right and !found )
  19.     {
  20.         mid = (left + right) / 2;
  21.         if (key == arr[mid]) { found = true; }
  22.         if (key > arr[mid]) { left = mid + 1; std::cout << "Right side...\n"; }
  23.         if (key < arr[mid]) { right = mid - 1; std::cout << "Left side...\n"; }
  24.     }
  25.  
  26.     if (found)
  27.     {
  28.         std::cout << "Found key = " << key << " in array!\n";
  29.     }
  30.     else
  31.     {
  32.         std::cout << "NOT Found key = " << key << " in array!\n";
  33.     }
  34. }
RAW Paste Data