Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "iostream"
- using namespace std;
- int main()
- {
- bool found = false;
- const int arraySize = 13;
- int a[arraySize] = {1,5,15,19,25,27,29,31,33,45,55,88,100};
- int key,low = 0,middle,high = (arraySize - 1);
- cout <<"Enter search key: ";
- cin >> key;
- while(low <= high)
- {
- middle = (low+high)/2;
- if(key == a[middle])
- {
- found = true;
- cout <<"Found element "<<key<<" at index "<<middle<<endl;
- break;
- }
- else if (key < a[middle])
- {
- high = middle - 1; // search low end of array
- }
- else
- {
- low = middle + 1; // search high end of array
- }
- }
- if(!found)
- {
- cout <<"Could not find element "<<key<<" in array a"<<endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement