C++ Programming Develop a program to perform a binary search on a one-dimensiona
ID: 3826021 • Letter: C
Question
C++ Programming
Develop a program to perform a binary search on a one-dimensional integer array LIST of dimension N. You should develop an independent search function (call it BinSearch), and write your program so that the BinSearch function is called from your main program. The BinSearch function should accept a search key parameter and return a Boolean value (Success). Maintain a count of the number of comparisons attempted during the execution of the function. Assume the array is already sorted in ascending order, and that there are no duplicate entries.
Explanation / Answer
Program:-
#include<iostream>
using namespace std;
int main()
{
int BinSearch (int [],int,int);
int n,i,list[100],key,result;
cout<<"Enter the number of elements in array: ";
cin>>n;
cout<<" Enter Elements of Array in Ascending order ";
for(i=0;i<n;++i)
{
cin>>list[i];
}
cout<<" Enter the key value to search:";
cin>>key;
result=BinSearch(list,n,key);
if(result!=-1)
cout<<" Key value is found at position "<<result+1;
else
cout<<" Key value is not present in the list!";
return 0;
}
int BinSearch(int list[],int n,int key)
{
int first,last,middle;
first=0;
last=n-1;
while(first<=last)
{
middle=(first+last)/2;
if(key==list[middle])
return(middle);
else
if(key>list[middle])
first=middle+1;
else
last=middle-1;
}
return -1;
}
Output:-
Enter the number of elements in array:
5
Enter Elements of Array in Ascending order
12
23
34
45
56
Enter the key value to search:34
Key value is found at position 3
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.