Write a program to find the location of a given element using Binary Search
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int arr[100],beg,mid,end,i,n,num;
cout<<"Enter the size of an array ";
cin>>n;
cout<<"\nEnter the values in sorted order (asc or desc) \n";
for(i=0;i<n;i++)
{
cin>>arr[i];
}
beg=0;
end=n-1;
cout<<"\nEnter a value to be searched in an array ";
cin>>num;
while(beg<=end)
{
mid=(beg+end)/2;
if(arr[mid]==num)
{
cout<<"\nItem found at position "<<(mid+1);
break;
}
else if(num>arr[mid])
{
beg=mid+1;
}
else if(num<arr[mid])
{
end=mid-1;
}
else
{
cout<<"Number does not found.";
}
}
cout<<"\n/*\nName-Sanjampreet Singh\nRoll Number-1507967\n*/";
return 0;
}
#include<conio.h>
using namespace std;
int main()
{
int arr[100],beg,mid,end,i,n,num;
cout<<"Enter the size of an array ";
cin>>n;
cout<<"\nEnter the values in sorted order (asc or desc) \n";
for(i=0;i<n;i++)
{
cin>>arr[i];
}
beg=0;
end=n-1;
cout<<"\nEnter a value to be searched in an array ";
cin>>num;
while(beg<=end)
{
mid=(beg+end)/2;
if(arr[mid]==num)
{
cout<<"\nItem found at position "<<(mid+1);
break;
}
else if(num>arr[mid])
{
beg=mid+1;
}
else if(num<arr[mid])
{
end=mid-1;
}
else
{
cout<<"Number does not found.";
}
}
cout<<"\n/*\nName-Sanjampreet Singh\nRoll Number-1507967\n*/";
return 0;
}
Comments
Post a Comment