-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.cpp
More file actions
77 lines (70 loc) · 1.76 KB
/
binary_search.cpp
File metadata and controls
77 lines (70 loc) · 1.76 KB
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
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
int binary_search(const vector<int>& lst, int start, int stop, int key) {
if (start > stop) {
return -1;
} else {
int mid = (start + stop) / 2;
if (key == lst[mid]) {
return mid;
} else if (key < lst[mid]) {
return binary_search(lst, start, mid - 1, key);
} else {
return binary_search(lst, mid + 1, stop, key);
}
}
}
void sort(vector<int>& lst) {
for (size_t i = 0; i < lst.size(); i++) {
for (size_t j = 0; j < lst.size() - 1; j++) {
if (lst[j] > lst[j + 1]) {
int temp = lst[j];
lst[j] = lst[j + 1];
lst[j + 1] = temp;
}
}
}
}
void main_program() {
string input;
cout << "Enter the list of numbers separated by hyphens: ";
cin >> input;
stringstream ss(input);
vector<int> lst;
while (ss.good()) {
string substr;
getline(ss, substr, '-');
lst.push_back(stoi(substr));
}
cout << "Unsorted list is [ ";
for (const auto& num : lst) {
cout << num << " ";
}
cout << "]" << endl;
sort(lst);
cout << "Sorted list is [ ";
for (const auto& num : lst) {
cout << num << " ";
}
cout << "]" << endl;
int key;
cout << "Enter value to find: ";
cin >> key;
int res = binary_search(lst, 0, lst.size() - 1, key);
if (res != -1) {
cout << "Element found at index " << res << endl;
} else {
cout << "Element not found" << endl;
}
}
int main() {
int n;
cout << "Enter the number of test cases: ";
cin >> n;
for (int i = 0; i < n; i++) {
main_program();
}
return 0;
}