Académique Documents
Professionnel Documents
Culture Documents
algorithm.
Objective:
The objectives of this program are:
1. Insert some data.
2. Sorting inserted data.
3. Insert the item.
4. Find the location of a given item using binary search algorithm.
Algorithm:
Binary Search:
1 Algorithm BinSrch (a, i, l, x)
2 // Given an array a[i : l] of elements in non-decreasing
3 // order, 1 ≤ i ≤ l, determine whether x is present, and
4 // if so, return j such that x= [j]; else return o.
5 {
6 if (l=i) then // If small (p)
7 {
8 if (x=a[i]) then return i;
9 else return 0;
10 }
11 else
12 { // Reduce P into a smaller sub problem
13 mid:= (i + l)/2 ;
14 if (x=a[mid]) then return mid;
15 else if (x<a[mid]) then
16 return BinSrch (a, i, mid-1, x)
17 else return BinSrch (a, mid+1, l, x)
18 }
19 } //main
Source Code:
#include<iostream.h>
#include<stdlib.h>
int bsearch(int x,int A[ ],int n)
{
int low=0, high=n-1,mid,found=0;
int comparisons=0;
while((low<=high)&&!found)
{
mid=(low+high)/2;
comparisons++;
if(x>A[mid])
low=mid+1;
else if(x<A[mid])
high=mid-1;
else
found=1;
}
if(found)
{
cout<<"Number of Comparison Required = "<<comparisons<<endl;
return mid;
}
else
{
cout<<"Number of Comparison Required = "<<comparisons<<endl;
return -1;
}
}//end of bsearch
void main( )
{
int A[1000],n,x,found,temp,j;
mm:;
cout<<"How many data you want to input : ";
cin>>n;
cout<<endl<<endl;
for(int i=0;i<n;i++)
{
cout<<"Data "<<i+1<<" = ";
cin>>A[i];
}
for(i=0;i<n-1;i++)
for( j=i+1;j<n;j++)
{
if(A[i]>A[j])
{
temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}//end of inner for
case 2:
exit(0);
}
}//end of main
Sample Input/output: