Programming Examples
Cpp program to search an element in a sorted array using function
write a program to search(binary)an element in an array using function
Solution
#include<iostream>
using namespace std;
int Bsearch(int[],int,int);
int main(){
int arr[50],ITEM,index,n;
cout<<"Enter the desired array size";
cin>>n;
cout<<"Enter the elements";
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"Enter the element to be searched for :";
cin>>ITEM;
index=Bsearch(arr,n,ITEM);
//cout<<" Index is: "<< index;
if(index==-1)
{
cout<<" Element cannot be found"<<endl;
}
else
{
cout<<"Element found at index "<<index<<",position "<<index+1<<endl;
return 0;
}
}
int Bsearch(int arr[],int size, int item)
{
int upper,lower=0,mid;
upper=size-1;
while(lower<=upper)
{
mid=(upper+lower)/2;
if(item==arr[mid])
{
return mid;
}
else if(item<arr[mid])
{
upper=mid-1;
}
else
{
lower=mid+1;
}
}
return -1;
}
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