Binary Search Program in C

In this post, we will write a C program for the binary search algorithm.

The binary search uses the divide and conquer approach. The item to be searched for is compared with the middle item in an array or file. This helps in determining which half of the array or file might contain the item being searched for. After that, the middle value of the half that was considered is compared with the item being searched for to determine which quarter part of the array or file might contain the item being searched for. The process continues until either the item being searched for is found, or no more divisions of the array or file are possible, in which case, it is understood that the item being searched for is not present in the file or array.

Binary Search Program in C

Let's create a file named binarysearch.c and add the following source code to it:
#include <stdio.h>
#define max 20

int binary_search(int[], int, int);

int main()
{
int len,found,numb,arr[max],i;
printf("Enter the length of an array: ");
scanf("%d",&len);
printf("Enter %d values in sorted order \n", len);
for(i=0;i< len;i++)
scanf("%d",&arr[i]);
printf("Enter the value to search ");
scanf("%d",&numb);
found=binary_search(arr,numb,len);
if(found==numb)
printf("Value %d is found in the list\n",numb);
else
return 0;
}

int binary_search(int arr[], int pnumb,int plen)
{
int lindex=0,mid,uindex=plen, nfound;
while(uindex >=lindex)
{
mid=(uindex+lindex)/2;
if(pnumb==arr[mid])
{
nfound=arr[mid];
break;
}
else
{
if(pnumb>arr[mid])
lindex=mid+1;
else
uindex=mid-1;
}
}
return(nfound);
}

To compile and run the above C program, you can use C Programs Compiler Online tool.

Output:

Enter the length of an array: 5
Enter 5 values in sorted order
10
20
30
40
50
Enter the value to search 20
Value 20 is found in the list