Binary Search

In this searching technique, the given element is compared with the middle element of the list.

• If both elements are equal, it returns the index value.
• If both elements are not equal, we check whether the given element is larger or smaller than the middle element.
• If the given element is smaller than the middle element, we will repeat the same process in the smaller part of the list.
• If the given element is larger than the middle element, we will repeat the same process in the larger part of the list.

For example, suppose you have the following array, and you have to search 30 in it.

Binary search program in C language

```#include<stdio.h>
int binarySearch(int[], int, int, int);
void main ()
{
int arr[10] = {6,  9, 12, 23, 35, 46, 68, 90, 96, 120};
int item, location=-1;
printf("enter the search element ");
scanf("%d",&item);
location = binarySearch(arr, 0, 9, item);
if(location != -1)
{
printf("element index value is %d",location);
}
else
{
printf("element not found");
}
}
int binarySearch(int a[], int beg, int end, int item)
{
int mid;
if(end >= beg)
{
mid = (beg + end)/2;
if(a[mid] == item)
{
return mid+1;
}
else if(a[mid] < item)
{
return binarySearch(a,mid+1,end,item);
}
else
{
return binarySearch(a,beg,mid-1,item);
}
}
return -1;
}
```

Output