C program:Implementation of Binary Search using recursion


Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm works on the principle of divide and conquer. For this algorithm to work properly, the data collection should be in the sorted form.

PROGRAM:

#include <stdio.h>

void ReadArray(int a[10],int n)
{
    int i;
    printf("\nEnter elements");
    for(i=0;i<n;i++)
    scanf("%d",&a[i]);
}

int binarysearch(int a[10], int low, int high, int x) {
   int mid = (low + high) / 2;
   if (low > high) return -1;
   if (a[mid] == x) return mid;
 
   if (a[mid] < x)
     return binarysearch(a, mid + 1, high, x);
   else
     return binarysearch(a, low, mid-1, x);
}

int main(void) {
  int a[100];
  int n, pos, search_item;

  printf("Enter the length of the array\n");
  scanf("%d", &n);
  ReadArray(a,n);

  printf("Enter the element to search\n");
  scanf("%d", &search_item);

  pos = binarysearch(a,0,n-1,search_item);

  if (pos < 0 )
    printf("Cannot find the element %d in the array.\n", search_item);

  else
    printf("The position of %d in the array is %d.\n", search_item, pos+1);
 
  return 0;
Previous Post Next Post