

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The implementation of a binary search algorithm in c++. The user is prompted to enter the number of elements in the array and each element, followed by the number to be searched. The algorithm then performs a binary search on the array to find the location of the number, if it exists.
Typology: Thesis
1 / 2
This page cannot be seen from the preview
Don't miss anything!


using namespace std;
int main() { int count, i, arr[30], num, first, last, middle; cout<<"how many elements would you like to enter?:"; cin>>count;
for (i=0; i<count; i++) { cout<<"Enter number "<<(i+1)<<": "; cin>>arr[i]; } cout<<"Enter the number that you want to search:"; cin>>num; first = 0; last = count-1; middle = (first+last)/2; while (first <= last) { if(arr[middle] < num) { first = middle + 1;
else if(arr[middle] == num) { cout<<num<<" found in the array at the location "<<middle+1<<"\n"; break; } else { last = middle - 1; } middle = (first + last)/2; } if(first > last) { cout<<num<<" not found in the array"; } return 0; } Output:
how many elements would you like to enter?: Enter number 1: 12 Enter number 2: 45 Enter number 3: 8 Enter number 4: 9 Enter number 5: 100 Enter the number that you want to search: 8 found in the array at the location 3