The ones who are crazy enough to think they can change the world are the ones who do.
- Steve Jobs

# Binary Search

Binary search, also called as half-interval search or logarithmic search, because it works efficiently with a sorted list. The working of binary search can be clearly understood by an analogy of alphabets in English.

step 1: Choose which letter in alphabets is to find using binary search say "L".

step 2: In binary search, the searching point moves to the middle element in of the alphabets say "M" and then decide which direction the searching point is to move.

step 3: Either left or right. In this case the searching point moves towards left.

step 4: Hopefully, next element to the letter M is "L". Thus binary search algorithm utilized the time effectively to match the Key element (L) in the alphabets.

• When a key element matches the middle element in the array, then Binary search algorithm is best case because executing time of Binary search algorithm is 0 (log n), where n is the number of elements in an array.

• When a key element matches the first or last element in the array, then Binary search algorithm is best case because executing time of Binary search algorithm is 0 (log n), where n is the number of elements in an array.

## C program - Binary Search

Here is the program to demonstrate Binary Search.

binary-search.c
```#include <stdio.h>
int main()
{
int arry[10], key, i, n, beg, end, mid, found = 0;
printf("\n Enter the size of the array : ");
scanf("%d", &n);
printf("\n Enter %d elements in the array : \n",n);
for(i=0; i < n; i++)
{
scanf("%d", &arry[i]);
}
printf("\n Enter the key element that has to be search : ");
scanf("%d", &key);
beg= 0, end= n-1;
while ( beg <= end)
{
mid = (beg + end) / 2;
if(arry[mid] == key)
{
printf("\n %d is found in the array at position arry [%d]", key, mid);
found=1;
break;
}
else if(arry[mid] > key)
end = mid - 1;
else
beg = mid + 1;
}
if(beg > end && found == 0)
printf("\n %d does not exist in the array", key);
return 0;
}```
```Enter the size of the array : 5
Enter 5 elements in the array :
1 2 3 4 5
Enter the key element that has to be search : 3
3 is found in the array at position arry [2]```

#### Report Us

We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.

Report

We to update you