Searching for an item using binary search in C

Last Updated On Friday 12th Nov 2021

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

c binary search

  • This lets you determine which half of an array contains the item you are searching for.

  • Compare with the middle-value item to determine which part of the array contains the item.

  • The process continues until the item being found.

	#include <stdio.h>

#define max 20
int binary_search(int[], int, int);
int main() {
   int len, found, num, 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", & num);
   found = binary_search(arr, num, len);
   if (found == num)
      printf("Value %d is found in the list\n", num);
   else
      printf("Value %d is not found in the list \n", num);
   return 0;
}
int binary_search(int arr[], int  num, int plen) {
   int lindex = 0, mid, uindex = plen - 1, nfound;
   while (uindex >= lindex) {
      mid = (uindex + lindex) / 2;
      if ( num == arr[mid]) {
         nfound = arr[mid];
         break;
      } else {
         if ( num > arr[mid])
            lindex = mid + 1;
         else
            uindex = mid - 1;
      }
   }
   return (nfound);
}
	

OutPut

	// Enter the length of an array: 4
// Enter 4 values in sorted order
// 11
// 22
// 33
// 44
// Enter the value to search 33
// Value 33 is found in the list
	

OutPut

	// Enter the length of an array: 4
// Enter 4 values in sorted order
// 11
// 22
// 33
// 44
// Enter the value to search 123
// Value 123 is not found in the list