Binary Search In C Programming

Introduction
  • In the programming, I am going to explain how to find the binary search in C programming.
  • It is used for sorted arrays and compared to linear search, it is faster.
Software Requirements
  • Turbo C++ or C. 
Programming 
  1. #include < stdio.h >   
  2. int main()   
  3. {  
  4.     int c, first, last, middle, n, search, array[100];  
  5.     printf("Enter number of elements\n");  
  6.     scanf("%d", & n);  
  7.     printf("Enter %d integers\n", n);  
  8.     for (c = 0; c < n; c++) scanf("%d", & array[c]);  
  9.     printf("Enter value to find\n");  
  10.     scanf("%d", & search);  
  11.     first = 0;  
  12.     last = n - 1;  
  13.     middle = (first + last) / 2;  
  14.     while (first <= last)  
  15.     {  
  16.         if (array[middle] < search) first = middle + 1;  
  17.         else if (array[middle] == search) {  
  18.             printf("%d found at location %d.\n", search, middle + 1);  
  19.             break;  
  20.         } else last = middle - 1;  
  21.         middle = (first + last) / 2;  
  22.     }  
  23.     if (first > last) printf("Not found! %d is not present in the list.\n", search);  
  24.     return 0;  
  25. }  
Explanation
  • With the help of the programming given above, the binary search is used to find the desired element in the list.
  • If the element is searched, it can be printed.

    programming 

    programming
Output

Output
Next Recommended Reading
Finding Compound Interest In Programming