Binary Search: Search an element in sorted array recursively

C program for binary searching: Binary searching recursively program. Here is simple C program for binary searching using recursion.
Binary searching prerequisite's that array should be sorted. In unsorted array binary searching does not works.

C Program:

#include<stdio.h>
 
int BSearch(int arr[],int low,int high,int num)
{
	/*Function will return -1 if number is not
	present in array 
	For example if array is 1,2,3 and we are searching 
	for 4 then in first call mid= 2/2 =1 and number is 
	greater then arr[mid] = 2 then low will become 
	mid+1 = 2 now high = low
	in next call mid = 2+2/2 = 2 so number is 
	greater then arr[mid] = 3 now low will become 
	become mid+1 = 3  and high<low(2<3) so to terminate function 
	we use this if loop */
 
	if(high<low)
	return -1;
	/* For large high we use low+(high-low)/2
	because of overflow */
	/* If high is max value of integer and low is 
	half of high then if we add low+high it will  
	be overflow */
	int mid=(low+high)/2;
 
	if(arr[mid]==num)
	return mid;
	else
	if(arr[mid]<num)
	 return BSearch(arr,mid+1,high,num);
	else
	return BSearch(arr,low,mid-1,num);
}
 
int main()
{
	int arr[]={1,2,3,4,5,6,7,12,13,14};
 
	int size = sizeof(arr)/sizeof(arr[0]);
 
	int num;
 
	printf("Enter a number: ");
	scanf("%d",&num);
 
	int index = BSearch(arr,0,size-1,num);
 
	if(index==-1)
	printf("Number is not in array\n");
	else
	printf("number is at index %d ",index);
 
	return 0;
}

Related: Binary Searching iterative method

Popular posts from this blog