Explain Binary search in C language

CServer Side ProgrammingProgramming

Binary search method can be applied only to sorted list. The given list is divided into two equal parts. In the list, the key is compared with middle element.

Three situations may occur in binary search which are as follows −

  • If the middle element matches the key, then the search will end successfully here

  • If the middle element is greater than the key, then the search will proceed in the left partition

  • If the middle element is lower than the key, then the search will proceed in the right partition.

Input (i/p)

sorted list of elements, key.

Output (o/p)

  • Success − If key is found.
  • Unsuccessful − Otherwise.

Example

Following is the C program for binary search method −

#include<stdio.h>
int main(){
   int a[50], n, i, key, flag = 0, low, mid, high;
   printf("enter the no: of elements:");
   scanf ("%d",&n);
   printf("enter the elements:");
   for(i=0; i<n; i++)
      scanf( "%d", &a[i]);
   printf("enter a key element:");
   scanf ("%d", &key);
   low = 0;
   high = n-1;
   while (low<= high ){
      mid = (low + high) /2;
      if (a[mid] == key){
         flag = 1;
      break;
   } else {
      if (a[mid] > key)
         high = mid-1;
      else
         low = mid+1;
      }
   }
   if (flag == 1)
      printf ("search is successful");
   else
   printf("search is unsuccessful");
   return 0;
}

Output

When the above program is executed, it produces the following result −

enter the no: of elements:5
enter the elements:23
45
57
89
90
enter a key element:45
search is successful
raja
Published on 09-Mar-2021 11:06:16
Advertisements