-Write a program to perform a binary search on a one-dimensional integer array c
ID: 3622533 • Letter: #
Question
-Write a program to perform a binary search on a one-dimensional integer array called LIST of dimension N.-The array should be presorted (in ascending order, with no duplicate entry's)
-The independant search function should be called BinSearch and should be written so it can be called from the main program.
-BinSearch function should accept a search key parameter and return a Boolean value (Success)
-BinSearch should also maintain a count of the number of comparisons attempted during execution of the function.
Explanation / Answer
//TO WRITE A PROGRAM TO SEARCH FOR A GIVEN ELEMENT FROM AN ARRAY USING BINARY
//SEARCH TECHNIQUE
#include<iostream.h>
#include<conio.h>
int binsearch(int ar[],int size,int ele)
{ int lb=0,ub=size-1,mid; //lb=>lower bound,ub=>upper bound
while(lb<=ub)
{
mid=(lb+ub)/2;
if(ar[mid]==ele)
{
cout<<" SEARCH SUCCESSFUL";
return mid;
}
else
if(ar[mid]<ele)
lb=mid+1;
else
if(ar[mid]>ele)
ub=mid-1;
}
cout<<" SEARCH UNSUCCESSFUL";
return -1;
}
void sort(int ar[],int size) //sorts the array in ascending array using bubble sort
{
int temp;
for(int i=0;i<size;i++)
for(int j=0;j<size-i-1;j++)
if(ar[j]>ar[j+1])
{
temp=ar[j];
ar[j]=ar[j+1];
ar[j+1]=temp;
}
}
void display(int ar[],int size)
{
for(int i=0;i<size;i++)
cout<<' '<<ar[i];
}
void input(int ar[],int size)
{
for(int i=0;i<size;i++)
cin>>ar[i];
}
void main()
{
clrscr();
int size;
cout<<" ENTER THE NUMBER OF ELEMENTS REQUIRED IN THE ARRAY :";
cin>>size;
int *ar=new int(size);
cout<<" ENTER THE ELEMENTS OF THE ARRAY : ";
input(ar,size); //takes the input from the array
sort(ar,size); //sorts the array in the ascending order
display(ar,size);
int ele;
cout<<" ENTER THE ELEMENT TO BE FOUND : ";
cin>>ele;
if(binsearch(ar,size,ele)>0)
cout<< " Element Found at" << binsearch(ar,size,ele);
else cout<< " Elemment not found"<<endl;
getch();
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.