BINARY SEARCH-Binary search is another important searching technique. Binary search is done in case of arrays where data elements are present in sorted form .The array should be sorted in increasing or  decreasing order numerically or it may be sorted in an alphabetical order depending upon the type of array. Binary search is a logical approach of search and is more systematic than linear search .Size of the array is no constraint in case of binary search technique.
/*Program to find the location of an element in the array using BINARY SEARCH*/
#include<stdio.h>
#include<conio.h>
#include<process.h>
#define true 1
#define false 0
int arr[10],n,i,item,loc,flag = 0,low,high,middle;
void main()
{
clrscr();
printf("Enter size of array:");
scanf("%d", &n);
if(n>10)
{
printf("Entered value exceed the limit of array");
getch();
exit(0);
}
printf("\n Enter array elements....");
for(i=0;i<=n-1;i++)
scanf("%d",&arr[i]);
printf("Enter the element to be searched...");
scanf("%d",&item);
//LOGIC of BINARY SEARCH
low = 0;
high = n-1;
while(low <= high && flag == 0)
{
middle = int((low+high)/2);
if(item<arr[middle])
high = middle-1;
else if(item>arr[middle])
low = middle+1;
else
{
flag = 1;
loc = middle;
break;
}
}
if(flag==1)
printf("\nElement found at location %d",loc);
else
printf("\nElement not found...");
getch();
}
/*Program to find the location of an element in the array using BINARY SEARCH*/
#include<stdio.h>
#include<conio.h>
#include<process.h>
#define true 1
#define false 0
int arr[10],n,i,item,loc,flag = 0,low,high,middle;
void main()
{
clrscr();
printf("Enter size of array:");
scanf("%d", &n);
if(n>10)
{
printf("Entered value exceed the limit of array");
getch();
exit(0);
}
printf("\n Enter array elements....");
for(i=0;i<=n-1;i++)
scanf("%d",&arr[i]);
printf("Enter the element to be searched...");
scanf("%d",&item);
//LOGIC of BINARY SEARCH
low = 0;
high = n-1;
while(low <= high && flag == 0)
{
middle = int((low+high)/2);
if(item<arr[middle])
high = middle-1;
else if(item>arr[middle])
low = middle+1;
else
{
flag = 1;
loc = middle;
break;
}
}
if(flag==1)
printf("\nElement found at location %d",loc);
else
printf("\nElement not found...");
getch();
}
 
No comments:
Post a Comment