Binary Search

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
int binSearch(int*,int,int);
void main()
{
	int *arr,size,i,searchEle,pos;
	clrscr();
	printf("\nEnter Size Of The Array: ");
	scanf("%d",&size);
	arr=(int *)calloc(size,sizeof(int));
	printf("\nEnter Elements: \n");
	for(i=0;i<size;i++)
		scanf("%d",(arr+i));
	printf("\nEnter Element To Be Searched: ");
	scanf("%d",&searchEle);
	pos=binSearch(arr,size,searchEle);
	if(pos==size)
		printf("\nElement Not Found.");
	else
		printf("\nElement Found At %d Position.",pos);
	getch();
}/*End of void main()*/
int binSearch(int *arr,int size,int searchEle)
{
	//int pos,i=0;
	int mid,beg=0,end=size-1;
	while(beg<=end && arr[mid]!=searchEle)
	{
		mid=(beg+end)/2;
		if(searchEle>arr[mid])
			beg=mid+1;
		else if(searchEle<arr[mid])
			end=mid-1;
	}/*End of while(beg>end && arr[mid]!=searchEle)*/
	if(beg>end)
		return size;
	else
		return mid;
}/*End of int binSearch(int *,int,int)*/

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *