-
Notifications
You must be signed in to change notification settings - Fork 2
/
BSearch
65 lines (64 loc) · 1.1 KB
/
BSearch
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Binary Search using recursion:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
int *a,cnt=0;
int binsrch(int low, int high, int x);
void main()
{
int i,n,num,pos;
char ans;
clrscr();
printf(" Enter size of an array: ");
scanf("%d",&n);
a = (int *) malloc(n);
printf("\n Enter %d integers in ascending order:",n);
for(i=1;i<=n;i++)
scanf("%d", &a[i]);
do
{
printf("\n Enter integer to be searched : ");
scanf("%d",&num);
printf("\n low high mid a[mid]");
pos=binsrch(1,n,num);
if(pos==0)
printf(" \n\n %d not found .",num);
else
printf(" \n\n %d Found at %d",num,pos);
printf(" \n\n Number of comparisions: %d", cnt);
cnt=0;
printf("\n Do u want to cnt....");
flushall();
ans = getche();
} while(ans=='y');
}
int binsrch(int low, int high, int x)
{
int mid;
if(low<=high)
{
mid = (low+high)/2;
cnt++;
if(a[mid]==x)
{
printf("\n%5d %5d %5d %5d",low,high,mid,a[mid]);
return (mid);
}
else
if(a[mid]<x)
{
printf("\n%5d %5d %5d %5d",low,high,mid,a[mid]);
binsrch (mid+1, high,x);
}
else
{
printf("\n%5d %5d %5d %5d",low,high,mid,a[mid]);
binsrch(low,mid-1,x);
}
}
else
{
printf("\n%5d %5d",low,high);
return 0;
}
}