Programming with C

⌘K
  1. Home
  2. Docs
  3. Programming with C
  4. Functions and Pointers
  5. Recursion
  6. Binary Search using Recursive Functions

Binary Search using Recursive Functions

Binary Search using Recursive Functions

#include<stdio.h>
int binarysearch(int list[], int low, int high, int key);
int main()
{
	int list[20], num, i, key, low, high, index;
	printf("Enter the number of elements:");
	scanf("%d",&num);
	printf("Enter the elements in ascending order:");
	for(i=0;i<num;i++)
	{
		scanf("%d",&list[i]);
	}
	printf("Enter the key you want to search:");
	scanf("%d",&key);
	index = binarysearch(list, 0,num-1, key);
	if(index == -1)
	{
		printf("%d does not exist in the list", key);
	}
	else
	{
		printf("%d exists at index  %d\n", key, index+1);
	}
	return 0;
}
int binarysearch(int list[], int low, int high, int key)
{
	int mid;
	if(low == high) // there is only one element
	{
		if(list[low] == key) // if that element is equal to the key
		{
			return low;
		}
		else // key is not present in the list
		{
			return -1; 
		}
	}
	else
	{
		mid = (low+high)/2;
		if(list[mid] == key)
		{
			return mid;
		}
		else if(list[mid]>key)
		{
			return binarysearch(list,low,mid-1,key);
		}
		else
		{
			return binarysearch(list,mid+1, high, key);
		}
	}
}

Output

Enter the number of elements:5
Enter the elements in ascending order:10
20
30
40
50
Enter the key you want to search:40
40 exists at index  4

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments