DATA STRUCTURES



Admission Enquiry Form

Binary Search in an Array.

Linear search is good for unsorted arrays. Linear search method is slow in large arrays. If array is of large size but sorted, we can use Binary search. It increases the speed of search operation.

binary search in array by compuhelp binary search in array by compuhelp

Algorithm of Binary Search in an Array

Step1. START

Step2.  LOC <- -1 [Initialize Location Counter]

Step3.  BEG <- 1, END <- N [Initialize]  

Step4.  [Search for ITEM]

              Repeat steps 5 and 6 while BEG <= END[Traverse]

Step5.   MID <- (BEG+END)/2

Step6.   If ITEM <- A[MID] then [Item found]

                            LOC <- MID

                            Exit loop

              Else If  ITEM > A[MID] then [Look in second half]

                             BEG <- MID + 1

              Else      [or Look in first half]

                             END <- MID-1

              [End of If Structure]

              [End of Step4 Loop]

Step7.   END Algorithm



Program of Binary Search in an Array.

#include<stdio.h>
#include<conio.h>
int main()
{
int arr[50],i,item,n,loc,flag=0;
int beg=0,end,mid;
printf("Enter the number of elements :\n");
scanf("%d",&n);
end=n-1;
printf("Enter the array elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("Enter item to be searched:\n");
scanf("%d",&item);
while(beg<=end)
{
mid=(beg+end)/2;
if(item==arr[mid])
{
flag=1;
loc=mid;
printf("Item found at loc %d",loc+1);
break;
}
else if(item<arr[mid])
{
end=mid-1;
}
else
{
beg=mid+1;
}
}
if(flag==0)
{
printf("Element is not found....");
}
getch();
}//end of main function