Searching algorithm: binary search in C

Binary search is a searching algorithm by which we can find any element in an array. At first we have to  sort the array using any sorting algorithms. We recommend you to learn sorting algorithm first.

In this article we will learn about binary search in C. We will print the location if find the number which we are searching. Let’s go to the program.

C program with binary search in C

// binary search c program

#include <stdio.h>
int main(){
  int first, mid, last, k, search, total_element, myArr[50];

  printf("Enter the number of element in the array : ");
  scanf("%d", &total_element);

  printf("\nEnter %d integers of array : \n", total_element);

  for (k = 0; k < total_element; k++)
    scanf("%d", &myArr[k]);

  printf("\nEnter the integer to find in the array : ");
  scanf("%d", &search);

  first = 0;
  last = total_element - 1;
  mid = (first + last) / 2;

  while (first <= last){
    if (myArr[mid] < search){
      first = mid + 1;
      
    }else if(myArr[mid] == search){
      printf("\nThe integer %d found at location %d.\n", search, mid + 1);
      break;
      
    }else{
      last = mid - 1;
    }
    
    mid = (first + last) / 2;
    
  }
  
  if (first > last){
    printf("\nThe integer %d does not found in array.\n", search);
  }
  
  return 0;
}

Output of binary search program :

binary-search-in-c-c-binary-search-program-1

Binary search using recursion in C

// binary search using recursion in c

#include <stdio.h>

int binarySearchFunct(int arr_of_int[], int first, int last, int find){
  int x;

  if(first > last){
     return -1;
  }

  x = (first + last)/2;

  if(arr_of_int[x] == find){
    return x;

  }else if (find > arr_of_int[x]){
    return binarySearchFunct(arr_of_int, x+1, last, find);

  }else{
    return binarySearchFunct(arr_of_int, first, x-1, find);
  }

}

int main(){
  int fNum, lNum, k, totalNum, myarr[50], search, index;

  printf("Enter the number of element in the array : ");
  scanf("%d", &totalNum);

  printf("Enter all the integers of array here : \n");

  for(k = 0; k < totalNum; k++){
    scanf("%d", &myarr[k]);
  }

  printf("Enter the number you want to find : ");
  scanf("%d", &search);

  fNum = 0;
  lNum = totalNum - 1;

  index = binarySearchFunct(myarr, fNum, lNum, search);

  if (index == -1){
    printf("\n%d is not present in array.\n", search);
  }else{
    printf("\n%d is found at index %d.\n", search, index);
 }
  return 0;
}

Program output :

Enter the number of element in the array : 7
Enter all the integers of array here :
2 4 5 7 8 9 12
Enter the number you want to find : 15

15 is not present in array.
Enter the number of element in the array : 7
Enter all the integers of array here :
2 4 5 7 8 9 12
Enter the number you want to find : 8

8 is found at index 4.

Previous pageQuick sort

Next pageLinear search