c++ program-linear and binary search by harikumaru

VIEWS: 140 PAGES: 4

More Info
									                                          Linear Search

//Program name:Linear search
//Author name :
//Created on :27/03/10
//Compiled on :27/03/10
//Objective : To search an element in the array

#include<iostream>
using namespace std;
int main()
{
  int a[50],n,i,t;
  cout<<"Enter the size of the array\n";
  cin>>n;
  cout<<"Enter the elements\n";
  for(i=0;i<n;i++)
    cin>>a[i];
  cout<<"Enter the number to be searched\n";
  cin>>t;
  for(i=0;i<n&&t!=a[i];i++);
  if(i<n)
    cout<<"Number found\n"<<endl;
  else
    cout<<"Number Not found\n"<<endl;
  return 0;
}


    OUTPUT


Enter the size of the array
4
Enter the elements
2567
Enter the number to be searched
6
Number found
                               Binary Search


//Binary search
//program name : bin.cpp
//author name :
//Date written : 27-01-2010
//Date compiled : 27-01-2010
//Revision History
// 1.o

#include<iostream>
using namespace std;
main()
{
int a[100],i,n,g,low,h,m;
cout<<"enter no of elements\n";
cin>>n;
cout<<"Enter "<<n<<" integer elements in ascending order\n";
for(i=0;i<n;i++)
cin>>a[i];
cout<<"\nEnter element to be searched ";
cin>>g;
low=0;
h=n-1;
while(low<=h)
{
m=(low+h)/2;
if(g==a[m])
{
 cout<<"Index is "<<m<<"\n";
break;
}
if(g>a[m])
low=m+1;
else
h=m-1;

cout<<g<<" not found\n";
}
}


 OUTPUT
enter no of elements
3
Enter 3 integer elements in ascending order
 123
Enter element to be searched 2
Index is 1

								
To top