forked from a-r-nida/HactoberFest2020-Beginers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
searching.cpp
87 lines (73 loc) · 1.93 KB
/
searching.cpp
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
#include <iostream>
using namespace std;
int main()
{
int choice, index, search, size, flag = 0;
cout << "Enter the size array" << endl;
cin >> size;
int A[size];
cout << "Enter the array in sorted order" << endl;
for (int i = 0; i < size; i++)
{
cin >> A[i];
}
cout << "Enter the Element to be searched" << endl;
cin >> search;
while (true)
{
cout << "MENU" << endl;
cout << "Enter 1 for Linear Search" << endl;
cout << "Enter 2 for Binary Search" << endl;
cout << "Enter 3 to exit" << endl;
cin >> choice;
switch (choice)
{
case 1:
{
cout << "Linear Search" << endl;
for (int j = 0; j < size; j++)
{
if (A[j] == search)
{
index = j;
flag = 1;
}
}
if (flag == 1)
{
cout << search << " is found at the index " << index << endl;
}
else
{
cout << search << " is not found in the array" << endl;
}
break;
}
case 2:
{
cout << "Binary Search" << endl;
int low = 0;
int high = size - 1;
while (low <= high)
{
int mid = low + (high - low) / 2;
if (A[mid] == search)
cout << search << " Element found at index " << mid << endl;
if (A[mid] <= search)
low = mid + 1;
else
high = mid - 1;
}
break;
}
case 3:
{
exit(0);
}
default:
{
cout << "No correct option chosen" << endl;
}
}
}
}