Vous êtes sur la page 1sur 4

Write a C program to find the location of an item using binary search

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

cout<<"Sorted Data : "<<endl;


for(i=0;i<n;i++)
cout<<A[i]<<endl;
cout<<"Enter data you want to find."<<endl;
cin>>x;
found=bsearch(x,A,n);
if(found==-1)
cout<<"Data "<<x<<" does not found"<<endl;
else
cout<<"Data "<<x<<" Found"<<endl;
cout<<"Do you want to process again (1 for yes & 2 for no)\n";
int ch;
cin>>ch;
switch(ch)
{
case 1:
goto mm;

case 2:
exit(0);
}
}//end of main

Sample Input/output:

Enter how many data you want to input : 5


Data 1 = 77
Data 2 = 11
Data 3 = 33
Data 4 = 22
Data 5 = 44
Sorted Data :
11
22
33
44
77
Enter data you want to find.
33
Number of Comparison Required = 1
Data 33 Found
Do you want to process again (1 for yes & 2 for no)
1
Enter how many data you want to input : 3
Data 1 = 66
Data 2 = 13
Data 3 = 34
Enter data you want to find.
55
Number of Comparison Required = 2
Data 55 does not found
Do you want to process again (1 for yes & 2 for no)
2

Vous aimerez peut-être aussi