-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinear_search_and_binary_search.c
101 lines (89 loc) · 2.09 KB
/
linear_search_and_binary_search.c
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include<stdio.h>
int i, j, n, a[100];
void entry()
{
printf("\nEnter no. of elements in the array: ");
scanf("%d", &n);
printf("\nEnter the elements: ");
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
}
void display()
{
for(i = 0; i < n; i++)
printf("%d\t", a[i]);
}
void lin_search()
{
int item;
printf("\nEnter element to search: ");
scanf("%d", &item);
for(i = 0; i < n; i++)
{
if(item == a[i])
{
printf("\nItem found at location %d.\n", i + 1);
return;
}
}
printf("\nItem not found.\n");
}
void bin_search()
{
int item, temp, beg, mid, end, flag = 0;
for(i = 0; i < n - 1; i++)
{
for(j = 0; j < n - i - 1; j++)
{
if(a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j+1] = temp;
}
}
}
printf("Array after sorting:\t");
display();
printf("\n\nEnter element to search: ");
scanf("%d", &item);
beg = 0;
end = n - 1;
while(beg <= end)
{
mid = (beg + end) / 2;
if(a[mid] == item)
{
printf("Item found at location %d.\n", mid + 1);
return;
}
else if(a[mid] < item)
beg = mid + 1;
else
end = mid - 1;
}
printf("\nItem not found.\n");
}
void main()
{
int ch;
do
{
printf("\n\t\t\tMENU\n");
printf("1. Entry\t2. Display\t3. Linear search\n\t4. Binary Search\t5. Exit\n");
printf("Enter choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1: entry();
break;
case 2: printf("Array:\t");
display();
break;
case 3: lin_search();
break;
case 4: bin_search();
break;
}
} while (ch >= 1 && ch <= 4);
}