C LAB‎ > ‎(Sem2) Data Structures‎ > ‎

Q4. WAP to perform binary search.

posted Jan 7, 2011, 11:43 PM by Neil Mathew   [ updated Jan 7, 2011, 11:50 PM ]

SOURCE CODE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include<stdio.h>
 
int Bsearch(int *a, int n, int item)
{
 
int beg,end,mid;
 
beg=0;
end=n-1;
 
while(beg<=end)
{
 
mid=(beg+end)/2;
 
if(a[mid]==item)
return mid;
else if(a[mid]>item)
end=mid-1;
else if(a[mid]<item)
beg=mid+1;
 
}
 
return -1;
}
 
 
main()
{
int a[50],n,i;
int item,pos;
 
printf("Enter size of your array: ");
scanf("%d",&n);
 
printf("Enter elements of your array: ");
for(i=0; i<n; i++)
scanf("%d",&a[i]);
 
printf("Enter item to search: ");
scanf("%d",&item);
 
pos=Bsearch(a,n,item);
 
if(pos==-1)
printf(" NOT FOUND. ");
else
printf(" FOUND AT %d", (pos+1));
 
}

OUTPUT:

Enter size of your array: 6
Enter elements of your array: 2 4 6 8 10 13
Enter item to search: 10
 FOUND AT 5
Comments