Binary Search:
Binary Search Technique is implemented on sorted list of elements. It is faster than linear search, hence this method is efficient when the number of elements are large.
Program:
#include<stdio.h>
#include<conio.h>
int binarysearch(in[],int,int,int);
void main( )
{
int a[20],val,i,n,low,high,bsf;
clrscr( );
printf("\nEnter the Number of Elements:");
scanf("%d",&n);
printf("\nEnter the %d of elements:",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nThe Elements in the array are :");
for(i=0;i<n;i++)
{
printf("\n%d",a[i]);
}
low=0;
high=n-1;
printf("\nEnter the Search Element:");
scanf("%d",&val);
bsf=binarysearch(a,val,low,high);
if(bsf == -1)
{
printf("\nElement is found");
}
else
{
printf("\nElement not found");
}
getch( );
}
int binarysearch(int a[ ], int val, int low, int high)
{
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==val)
{
return mid;
}
else if(a[mid]>val)
{
low=mid-1;
}
else if(a[mid]<val)
{
low=mid+1;
}
else
{
return -1;
}
}
return -1;
}
Output:
Enter the Number of Elements:5
Enter the 5 of elements:
1
2
3
4
5
The Elements in the array are :
1
2
3
4
5
Enter the Search Element:10
Element not found
Binary Search Technique is implemented on sorted list of elements. It is faster than linear search, hence this method is efficient when the number of elements are large.
Program:
#include<stdio.h>
#include<conio.h>
int binarysearch(in[],int,int,int);
void main( )
{
int a[20],val,i,n,low,high,bsf;
clrscr( );
printf("\nEnter the Number of Elements:");
scanf("%d",&n);
printf("\nEnter the %d of elements:",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nThe Elements in the array are :");
for(i=0;i<n;i++)
{
printf("\n%d",a[i]);
}
low=0;
high=n-1;
printf("\nEnter the Search Element:");
scanf("%d",&val);
bsf=binarysearch(a,val,low,high);
if(bsf == -1)
{
printf("\nElement is found");
}
else
{
printf("\nElement not found");
}
getch( );
}
int binarysearch(int a[ ], int val, int low, int high)
{
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==val)
{
return mid;
}
else if(a[mid]>val)
{
low=mid-1;
}
else if(a[mid]<val)
{
low=mid+1;
}
else
{
return -1;
}
}
return -1;
}
Output:
Enter the Number of Elements:5
Enter the 5 of elements:
1
2
3
4
5
The Elements in the array are :
1
2
3
4
5
Enter the Search Element:10
Element not found
0 comments:
Post a Comment