Program Code:
#include<iostream.h>
#include<conio.h>
int binarySearch(int a[],int,int);
main()
{
int arr[50],size,index,target;
cout<<"Enter the size of array(max 50):\n";
cin>>size;
cout<<"Enter the elements of the array:\n";
for(int i=0;i<size;i++)
{
cin>>arr[i];
}
cout<<"Enter the element to be searched:\n";
cin>>target;
index=binarySearch(arr,size,target);
if(index==-1)
{
cout<<"Element is not present in the list\n";
}
else
{
cout<<"Element is present at index "<<index+1;
}
getch();
}
int binarySearch(int a[],int s,int t)
{
int beg,last,mid;
beg=0;
last=s-1;
while(beg<=last)
{
mid=(beg+last)/2;
if(a[mid]==t)
{
return mid;
}
else if(t>a[mid])
{
beg=mid+1;
}
else
{
last=mid-1;
}
}
return -1;
}
Output:
0 comments:
Post a Comment