Write a C Program to search an element through binary search

Admin

Program to search an element through binary search

Write a C  Program to search an element through binary search


#include <stdio.h>
#define SIZE 100
int binary_search(int arr[],int item, int low, int high);
int main(void)
{
	int arr[SIZE],i, item, n;
	printf("Enter the number of elements : ");
	scanf("%d",&n);
	printf("Enter elements of the array(in sorted order) : \n");
	for(i=0; i<n; i++)
		scanf("%d",&arr[i]);
	printf("Enter the item to be searched : ");
	scanf("%d", &item);
	
	i=binary_search(arr,item,0,n-1);
	if(i==-1)
		printf("Not Present\n");
	else
		printf("Present at index %d\n",i);
	return 0;
}/*End of main()*/

int binary_search(int arr[],int item,int low,int up)
{
	int mid;
	if(up < low)
		return -1;	/*not found*/
	mid=(low+up)/2;
	if(item > arr[mid])
		return binary_search(arr,item,mid+1,up);	/*Search in right portion, tail recursive call*/
	else if(item  < arr[mid])
		return binary_search(arr,item,low,mid-1);	/*Search in left portion, tail recursive call*/
	else
		return mid;	/*found*/
}/*End of binary_search()*/

Output
Enter the number of elements : 5
Enter elements of the array(in sorted order) : 
19 20 21 22 23 24
Enter the item to be searched : Not Present

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.