u

Wednesday 6 June 2012

C++ Program to Searching element in an array using binary search

C++ Program to Searching element in an array using binary search


#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<process.h>
main()
{
clrscr();
int marks[100],x=0,i=0,n=0,middle=0,pos=0,first=0;
cout<<"Enter the number of elements required for storage";
cout<<endl;
cin>>n;
for(i=0;i<n;i++)
{
cout<<"Enter value ";
cin>>marks[i];
}
char op='y';
while ((op=='y') || (op=='Y'))
{
int last = n-1;
pos=-1;
cout<<"Enter the element to be searched";
cout<<endl;
cin>>x;
while((pos==-1)&&(first<=last))
{
// Application of binary search
middle=(first+last)/2;
if (marks[middle]==x)
{
pos=middle;
}
if(marks[middle]<x)
first=middle+1;
else
last=middle-1;
}
if (pos==-1)
cout<<"Sorry not present in the list"<<endl;
else
cout<<"The element lies in the array at position"<<pos+1;
cout<<endl;
cout<<"Enter option y/n";
cin>>op;
}
getch();
return 0;
}


0 comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More