Search



Thursday, 26 February 2015

binary search in array

In this program, the task is to take input of n no. of elements in , store it in array & then find whether the element entered by user is present in the array or not using binary search . Here , n is the no. of elements in array & Using for loop , we will get the values in order of a[0] , a[1] , - - - - till a[n] . Afterthat , we take input of the element to be searched . In binary search , we take 3 variables ( mid, end, beginning as(beg)) where mid  = (beg+end)/2 . 
Now check if value to be find is greater than mid or less if its greater then we check again in between end & mid or if the value is smaller then we will check between beg & mid & this will continue till the element is not found . This procedure is caleed as binary search . 
Binary search just decreases the complexity of program & no. of conditions that are checked in linear search . 


#include<stdio.h>
#include<conio.h>
void main()
{ int a[20],i=0,n,find,mid,beg,end,c=0;
clrscr();
printf("\n program to perform binary search in array");
printf("\n\n enter no. of elements in array (max 20) : ");
scanf("%d",&n);
printf(" now enter them : \n");
for(i=0;i<n;i++)
{ printf("enter a[%d] = ",i);
scanf("%d",&a[i]);
}
beg=0; end = n;
mid = (beg + end)/2;
printf("\n enter element to search : ");
scanf("%d",&find);
while(beg<=end)
{ mid = (beg + end)/2;
if(a[mid]<find)
beg = mid+1;
else if(a[mid]>find)
end = mid-1;
else if(a[mid]==find)
{     c=1;break; }
}
if(c==1)
{ printf("\n\n element (%d) found at position = %d",a[mid],mid);
}
else if(c==1)
printf("\n\n element not found in array");
getch();
}

No comments:

Post a Comment

Guys if you think something is wrong or should be edit than please do comment.