Programming Examples
Cpp program to search an element in an array using binary search
Write a program to search an element in a sorted array
Solution
#include<iostream>
using namespace std;
int main(){
int arr[50],size,i,item,upper,lower=0,mid,flag=0;
cout<<"Enter the desired array size "<<endl;
cin>>size;
cout<<"Enter the elements(Sorted in ascending order) "<<endl;
for(i=0;i<size;i++)
{
cin>>arr[i];
}
cout<<"Enter the element to be searched for :";
cin>>item;
upper=size-1;
while(lower<=upper)
{
mid=(upper+lower)/2;
if(item==arr[mid])
{
flag=1;
break;
}
else if(item<arr[mid])
{
upper=mid-1;
}
else
{
lower=mid+1;
}
}
if(flag==1)
{
cout<<"Element found at index "<<mid<<" position "<<mid+1;
}
else
{
cout<<"Element not found"<<endl;
}
return 0;
}
Output
Enter the desired array sizeÂ
10
Enter the elements(Sorted in ascending order)Â
2
3
5
9
12
15
20
23
25
30
Enter the element to be searched for :20
Element found at index 6 position 7