Example: Binary Search Program in C++ This program asks the user to input the number of elements and then the value of those elements. All the user entered numbers are stored in an array. The program then asks the user to input the search element (the number that needs to be searched in the list). The program searches the entered number in the list using binary search.
#include <iostream>
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?:5
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
8 found in the array at the location 3. plz give me the dry run of the program
Share
0 Replies