Techknow Study

C program : Binary search

4:24:00 PM Ashish Rana 0 Comments Category :



#include<stdio.h>
#include<conio.h>
binarysearch(int *[], int, int, int);
void main()
{
int i, j, k, t, low, high, n, a[50], ans;
clrscr();
printf(" \n Enter the number of elements: ");
scanf(" %d ", &n);
printf(" \n Enter the array element one by one \n ");
for(i = 0; i < n; i++)
scanf(" %d ", &a[i]);
printf(" \n Sorted array \n "); 
for(Ii= 0; i < n; i++) 
for(j = I + 1; j < n; j++) 
if(a[i] > a[j]) 

t = a[i]; 
a[i] = a[j]; 
a[j] = t; 

for(i =0; i < n; i++) 
printf(" \t a[%d] = %d \n ", i, a[i]); 
printf("\t Enter the element to search:"); 
scanf("%d",&k); 
low = 0; 
high = n - 1; 
ans = binarysearch(a, k, low, high); 
if(ans !=-1) 
printf(" \n The number %d is present in the list at location %d. ", k, ans); 
else printf(" The number is not present in the list. "); 
getch(); 

int binarysearch(int *a[], int x, int low, int high) 

int mid, p; 
if(low > high) 
return-1; 
while(low<=high) 

mid = (low + high) / 2; 
p = a[mid]; 
if(x == p)
return(mid); 
else if(x < p) high=mid-1; 
else low=mid+1; 
}
}

RELATED POSTS

0 comments