To Perform Binary Search > C Program

Analysis of Algoritm

To Perform Binary Search > C Program


#include<stdio.h>
#include<conio.h>
int binarysearch(int arr[],int n,int x);
void main()
{

int arr[20],n,i,p,x;
clrscr();
printf("Enter the number of elements of  array :");
scanf("%d",&n);
printf("The Sorted array is :\n");
for(i=0;i<n;i++)
{
printf("Enter element:");
scanf("%d",&arr[i]);
}
printf("Enter the element to be searched:");
scanf("%d",&x);
p=binarysearch(arr,n,x);
if(p==-1)
printf("Element not found");
else
printf("Element %d found at index %d",x,p);
getch();
}
int binarysearch(int arr[],int n,int x)
{
int low,high,mid;
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(x==arr[mid])
return mid;
else if(x<arr[mid])
high=mid-1;
else
low=mid+1;
}
return -1;
}

Comments

Popular posts from this blog

Intermediate Code Generation > C Program