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:
No comments:
Post a Comment
Feel free to ask us any question regarding this post