#include<iostream> using namespace std;
// find the key from a[first] to a[last]
// a[] : array, in ascending order
// first: index
// last: index
// key : the number to be searched
// found : true if the key is found, false otherwise
// location: location of the key in the array if the key is found
void search(const int a[], int first, int last,
int key, bool& found, int& location);
int main() {
int a[] = {2,3,5,7,11,13,19,23,29,31,37,41,43,47};
int size = 14;
int key, location;
bool found;
cout << "Enter a number to be located: ";
cin >> key;
search(a, 0, 13, key, found, location);
if(found) {
cout << key << " is in index location "
<< location << endl;
} else {
cout << key << " is not in the array." << endl;
}
return 0;
}
void search(const int a[], int first, int last,
int key, bool& found, int& location) {
int mid;
if(first > last) {
found = false;
} else {
mid = (first + last)/2;
if(key == a[mid]) {
found = true;
location = mid;
} else if (key < a[mid]) {
search(a, first, mid - 1, key, found, location);
} else if (key > a[mid]) {
search(a, mid + 1, last, key, found, location);
}
}
}
|