Tuesday 1 October 2013

c++ program to search an element in an array using binary search

#include<iostream.h>
#include<conio.h>
void main()
{
int arr[100],first=0,last=0,middle=0,n,search;
clrscr();
cout<<"enter the size of array";
cin>>n;
cout<<"enter the elements in ascending order";
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"\n"<<"enter the element to be searched";
cin>>search;
first=0;last=n-1;middle=(first+last)/2;
while(first<=last)
{
if(arr[middle]<search)
first=middle+1;
else if(arr[middle]==search)
{
cout<<"element found at position:"<<middle+1;
break;
}
else
last=middle-1;
middle=(first+last)/2;
}
getch();
}

No comments:

Post a Comment