aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAryadev Chavali <aryadev@aryadevchavali.com>2023-07-10 14:14:15 +0100
committerAryadev Chavali <aryadev@aryadevchavali.com>2023-07-10 14:14:15 +0100
commitd9e8ccb3b2dfbfbb5c506ce88a72e46b4fbb07fb (patch)
treecbf2ddd8acbc8d6dedf07435174c574e0b161039
parent5b05f2323c948b294d5ca793870b0d32eb235abc (diff)
downloadalgorithms-d9e8ccb3b2dfbfbb5c506ce88a72e46b4fbb07fb.tar.gz
algorithms-d9e8ccb3b2dfbfbb5c506ce88a72e46b4fbb07fb.tar.bz2
algorithms-d9e8ccb3b2dfbfbb5c506ce88a72e46b4fbb07fb.zip
(bsearch)+algorithm implementation
Reads lines from "bsearch.txt", asks user for a number then binary searches that number in the input data from "bsearch.txt".
-rw-r--r--bsearch.cpp57
1 files changed, 57 insertions, 0 deletions
diff --git a/bsearch.cpp b/bsearch.cpp
new file mode 100644
index 0000000..6172b15
--- /dev/null
+++ b/bsearch.cpp
@@ -0,0 +1,57 @@
+/* bsearch.cpp
+ * Created: 2023-07-10
+ * Author: Aryadev Chavali
+ */
+
+#include <algorithm>
+#include <cstdlib>
+#include <fstream>
+#include <iostream>
+#include <string>
+#include <vector>
+
+using std::cin;
+using std::cout;
+using std::endl;
+using std::ostream;
+using std::string;
+using std::vector;
+
+vector<int> arr;
+
+ostream &print_arr(ostream &os)
+{
+ os << "[";
+ for (size_t i = 0; i < arr.size(); ++i)
+ os << arr[i] << (i == arr.size() - 1 ? "" : ",");
+ return os << "]";
+}
+
+int bsearch(int n, int l = 0, int u = arr.size() - 1)
+{
+ int midpoint = ((u + l) / 2);
+ if (l >= u || u <= 0)
+ return -1;
+ int val = arr[midpoint];
+ if (val == n)
+ return midpoint;
+ else if (val > n)
+ return bsearch(n, l, midpoint - 1);
+ else
+ return bsearch(n, midpoint + 1, u);
+}
+
+int main(void)
+{
+ std::ifstream input("bsearch.txt");
+ string line;
+ while (std::getline(input, line))
+ arr.push_back(std::stoi(line));
+ std::sort(std::begin(arr), std::end(arr));
+ string inp;
+ cout << "Enter number to search: ";
+ cin >> inp;
+ int to_search = std::stoi(inp);
+ cout << bsearch(to_search) << endl;
+ return 0;
+}