Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#include <stdio.

h>
using namespace std;
#include<iostream>

int main()
{
int beg,end,item,mid,n;
int arr[n];
cout<<"Enter number of elements in array: ";
cin>>n;
cout<<"Enter "<<n<<" number of elements:";
for(int i = 0;i<n;i++)
cin>>arr[i];
cout<<"Enter the number you want to search: ";
cin>>item;
beg = 0;
end = n;
for(int i =0;i<n;i++)
{ mid = (beg+end)/2;
if(item == arr[mid])
{ break;
}
else if(item > arr[mid])
{ beg = mid+1;
end = end;
cout<<"Element found";
break;
}
else if(item < arr[mid])
{ end = mid-1;
beg = beg;
cout<<"Element found";
break;
}
else
cout<<"Element not found.";
}
cout<<"Element found at position "<<mid;
return 0;
}
#include <stdio.h>
using namespace std;
#include<iostream>
int BS(int a[],int beg,int item,int end)
{ int mid = (beg+end)/2;
if(item == a[mid])
{ cout<<"Element found at position : "<<mid;
}
else if(item < a[mid])
{
BS(a,beg,mid,mid-1);
}
else if(item < a[mid])
{
BS(a,mid+1,mid,end);
}
}
int main()
{
int beg,end,item,mid,n,result;
int arr[n];
cout<<"Enter number of elements in array: ";
cin>>n;
cout<<"Enter "<<n<<" number of elements:";
for(int i = 0;i<n;i++)
cin>>arr[i];
cout<<"Enter the number you want to search: ";
cin>>item;
beg = 0;
end = n;
result = BS(arr,beg,mid,end);
cout<<"Element found at position "<<result;
return 0;
}

You might also like