Ticker

6/recent/ticker-posts

Header Ads Widget

Binary search in an array : Bigfootcode

Binary Search in an array - Bigfootcode


Introduction
In this tutorial you will learn  how to search an array ,how to create a array and how to display array in one single program.



Theory
 In this program we first declare the all the variables required for storing, searching, and printing on the screen.

Here we our performming binary search which is faster then the linear search as in this case we don't need to compare all elements and this id different from linear case in various aspects let see that.
Q) what is difference between Linear and binary search.
Q) Linear search vs binary search
  • Array is already sorted in ascending order.
  • Comparison are less compare to Linear search.
  • Faster then linear search.

Q) write a program to search an linear array ?
Sol

#include<iostream.h>
#include<conio.h>
int Bsearch(int [],int,int  );
int main()
{
int a[100], size,item,n,index;
cout<<"enter the number of elment you want to insert: ";
cin>>size;
for(int i=1;i<=size; i++)
{
cout<<"enter elemnt number"<<i<<": ";
cin>> a[i];
}cout<<"your array is as shown below :\n";
for(int i=1;i<=size; i++)
{cout<<a[i];}
cout<<"\n Enter the element to search in an array:- \n";
cin>>item;
index =Bsearch(a,size,item  );
if(index==-1)
cout<<"\n element you Enter is not in an array:- \n";
else
cout<<"element found at index:"<<index<<endl;
return 0;
}

int Bsearch(int  a[],int size,int item)
{int beg ,last,mid;
beg =0; last=size-1;
while(beg<=last)
{mid=(beg+last)/2;
if(item==a[mid]) return mid;
else if (item>a[mid]) beg=mid +1;
else last=mid-1;}
return -1;
}



Now see the output

Output:



enter the number of elment you want to insert: 5
enter elemnt number1: 1
enter elemnt number2: 2
enter elemnt number3: 3
enter elemnt number4: 4
enter elemnt number5: 5
your array is as shown below :
12345
 Enter the element to search in an array:-
3
element found at index:3





Post a Comment

0 Comments