-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinear and binary search
More file actions
65 lines (65 loc) · 921 Bytes
/
linear and binary search
File metadata and controls
65 lines (65 loc) · 921 Bytes
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
#include<stdio.h>
void linear(int[] );
void binary(int[] );
int i,n;
void main()
{
int a[10],s;
printf("enter 0 for linear search and 1 for binary search");
scanf("%d", &s);
printf("enter the size of array");
scanf("%d",&n);
printf("enter the sorted elements");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
if(s==0)
linear(a);
else if(s==1)
binary(a);
else
printf("enter 1 or 0");
}
void linear(int b[])
{
int p,flag=0;
printf("enter the element to be searched");
scanf("%d",&p);
for(i=0;i<n;i++)
{
if(b[i]==p)
{
flag=1;
break;
}
}
printf("the element is found at %d", i+1);
}
void binary(int c[])
{
int low,high,mid,key,pos;
int q=0;
printf("enter the element to be searched");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==c[mid])
{
pos=mid;
q=1;
break;
}
else if(key>c[mid])
low=mid+1;
else
high=mid-1;
}
if(q==1)
printf("element is found at %d", pos);
else
printf("element not found");
}