Advertisement
ptrawt

259201 Lab13.1

Nov 13th, 2014
453
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.70 KB | None | 0 0
  1. #include "iostream"
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6.     bool found = false;
  7.     const int arraySize = 13;
  8.     int a[arraySize] = {1,5,15,19,25,27,29,31,33,45,55,88,100};
  9.     int key,low = 0,middle,high = (arraySize - 1);
  10.  
  11.     cout <<"Enter search key: ";
  12.     cin >> key;
  13.     while(low <= high)
  14.     {
  15.         middle = (low+high)/2;
  16.  
  17.         if(key == a[middle])
  18.         {
  19.             found = true;
  20.             cout <<"Found element "<<key<<" at index "<<middle<<endl;
  21.             break;
  22.         }
  23.         else if (key < a[middle])
  24.         {
  25.             high = middle - 1;          // search low end of array
  26.         }
  27.         else
  28.         {
  29.             low = middle + 1;           // search high end of array
  30.         }
  31.     }
  32.  
  33.     if(!found)
  34.     {
  35.         cout <<"Could not find element "<<key<<" in array a"<<endl;
  36.  
  37.     }
  38.  
  39.     return 0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement