Signup/Sign In

Binary Search Program In C Language

learn C language tutorial

Binary Search:

  • By using the binary search, the position of the element can be found in the sorted list,
  • Binary search will find the given element from the middle element of the sorted list,
  • You can learn more about Binary Search Algorithm from here.

C Language Program For Binary Search :

// Binary Search Using C

#include <stdio.h>

int binSea(int arr[], int i, int x, int y) {

  while (x<= y) {
    int m= x+ (y- x) / 2;

    if (arr[m] == i)
      return m;

    if (arr[m] < i)
      x= m+ 1;

    else
      y= m- 1;
  }

  return -1;
}

int main(void) {
  int arr[] = {12, 14, 17, 19, 20, 21, 22};
  int n = sizeof(arr) / sizeof(arr[0]);
  int i = 22;
  int result = binSea(arr, i, 0, n - 1);
  if (result == -1)
    printf("The Given Element Is Not Found In The Given Sorted List");
  else
    printf("The Given Element 22 Is Found At The Index Of %d", result);
  return 0;
}

Output:

Binary



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight