ASDV-Cpp/Assignments/MP2_CalebFontenot_clion/binarySearch.cpp

39 lines
958 B
C++
Raw Normal View History

2024-03-07 13:27:19 -06:00
#include <iostream>
#include <vector>
#include <climits>
2024-03-07 18:40:11 -06:00
#include <algorithm>
2024-03-10 00:49:58 -06:00
#include <tuple>
2024-03-07 13:27:19 -06:00
using namespace std;
2024-03-07 18:40:11 -06:00
int binarySearch(std::vector<int> arr, int numToSearchFor) {
std::sort(arr.begin(), arr.end());
2024-03-07 13:27:19 -06:00
int first = 0;
int last = arr.size() - 1;
2024-03-10 00:49:58 -06:00
int position = -1;
2024-03-07 13:27:19 -06:00
2024-03-10 00:49:58 -06:00
while (first <= last) {
int middle = first + (last - first) / 2;
2024-03-07 13:27:19 -06:00
if (arr[middle] == numToSearchFor) {
position = middle;
2024-03-10 00:49:58 -06:00
break;
2024-03-07 13:27:19 -06:00
}
2024-03-07 18:40:11 -06:00
else if (arr[middle] > numToSearchFor) {
last = middle - 1;
} else {
first = middle + 1;
}
2024-03-07 13:27:19 -06:00
}
2024-03-07 18:40:11 -06:00
return position;
2024-03-07 13:27:19 -06:00
}
2024-03-07 18:40:11 -06:00
std::tuple<int, int> binarySearch(std::vector<std::vector<int>> arr, int numToSearchFor) {
for (int i = 0; i < arr.size(); ++i) {
int columnLocation = binarySearch(arr[i], numToSearchFor);
2024-03-10 00:49:58 -06:00
if (columnLocation > -1) {
2024-03-07 18:40:11 -06:00
return {i, columnLocation};
}
}
2024-03-10 00:49:58 -06:00
return {-1, -1};
}