Write a C Program for Binary search in an array

#include #define MAX 50 int BinarySearch(int arr[],int size,int item); int main(void) { int i,size,item,arr[MAX],index; printf("Enter the
Admin

C Program for Binary search in an array

 This Program will Takes 3 inputs

  1. For the size of array
  2. Input for arrays
  3. Element to be searched in array
If element is available it will return index else -1.
#include <stdio.h>
#define MAX 50
int BinarySearch(int arr[],int size,int item);
int main(void)
{
	int i,size,item,arr[MAX],index;
	printf("Enter the number of elements : ");
	scanf("%d",&size);
	
	printf("Enter the elements(in sorted order) : \n");
	for(i=0; i<size; i++)
		scanf("%d",&arr[i]);

	printf("Enter the item to be searched : ");
	scanf("%d",&item);
	index=BinarySearch(arr,size,item);

	if(index==-1)
		printf("%d not found in array\n",item);
	else
		printf("%d found at position %d\n",item,index);
	return 0;
}
int BinarySearch(int arr[],int size,int item)
{
	int low=0,up=size-1,mid;
	while(low<=up)
	{
		mid=(low+up)/2;
		if(item > arr[mid])
			low=mid+1;	/*Search in right half*/
		else if(item < arr[mid])
			up=mid-1;	/*Search in left half*/
		else
			return mid;
	}
	return -1;
}

Output
Enter the number of elements : 4
Enter the elements(in sorted order) : 
11101
10001
11011
11111
Enter the item to be searched : 11111
11111 found at position 3

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.