C++ PRACTICAL PROGRAMS
Class 12 Computer Science | ASSEB
Program to search an element in an array using binary search
#include<iostream>
using namespace std;
int main( )
{
int a[50], n, key;
int low,high,mid;
cout<<”Enter number of elements”;
cin>>n;
cout<<”Enter elements in sorted order”;
for( int i=0; i<n; i++)
{
cin>>a[i];
}
cout<<”Enter element to search”;
cin>>key;
low=0;
high=n-1;
while (low<=high)
{
mid=(low+high)/2;
if(a[mid] == key)
{
cout<<”Element found at position”<<mid;
return 0;
}
else if(a[mid]<key)
low=mid+1;
else
high = mid – 1;
}
cout<<”Element not found”;
return 0;
}
Output
Enter number of elements 5
Enter elements in sorted order 2
3
5
7
9
Enter element to search 5
Element found at position 2
QUICK LINKS
Class 11
Class 12
Previous Year Paper
Practical Programs