Binary Search in C using Function Recursion

Binary Search in C using Function Recursion
     This binary search program is used to search position of entered number in an array. This program work by comparing middle element of array, if the condition is true it will print the position or else the mid will be shifted  If we compare time complexity of binary search with linear search, Binary search is more faster than linear search.
       In simple words recursion can be defined as calling a function again in a function.This program is best example to see how function recursion works.

Recommended: Binary search without recursion

Program:

#include<stdio.h>
#include<stdlib.h>
#define size 10
// C program of binary search using function recursion. SlashMyCode.com
int binsearch(int[], int, int, int);

int main()
{
   int num, i, key, position;
   int low, high, list[size];

   printf("\n Number of elements");
   scanf("%d", &num);

   printf("\n Enter the elements of list :");
   for (i = 0; i < num; i++)
        {
         scanf("%d",&list[i]);
        }

   low = 0;
   high = num - 1;

   printf("\n Enter element to be searched : ");
   scanf("%d", &key);

   position = binsearch(list, key, low, high);

   if (position != 1)
    {
      printf("\nNumber is present at %d", (position + 1));
   } else
      printf("\n The number is not present in the list");
   return (0);

}
// C program of binary search using function recursion. SlashMyCode.com
int binsearch(int a[], int x, int low, int high)
{
   int mid;

   if (low > high)
      return 1;

   mid = (low + high) / 2;

   if (x == a[mid]) {
      return (mid);
   } else if (x < a[mid]) {
      binsearch(a, x, low, mid - 1);
   } else {
      binsearch(a, x, mid + 1, high);
   }

}



Output:


Binary Search in C using Function Recursion

No comments:

Post a Comment

Feel free to ask us any question regarding this post