ASDV-Cpp/Assignments/MP2_CalebFontenot_clion/binarySearch.cpp

62 lines
1.5 KiB
C++
Raw Permalink 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-11 08:50:33 -05:00
bool found = false;
2024-03-07 13:27:19 -06:00
2024-03-11 08:50:33 -05:00
while (!found && first <= last) {
2024-03-10 00:49:58 -06:00
int middle = first + (last - first) / 2;
2024-03-07 13:27:19 -06:00
if (arr[middle] == numToSearchFor) {
2024-03-11 08:50:33 -05:00
found = true;
2024-03-07 13:27:19 -06:00
position = middle;
}
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-11 08:50:33 -05:00
if (!found) {
return -1;
} else {
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};
}
2024-03-11 08:50:33 -05:00
int linearSearch(std::vector<int> arr, int numToSearchFor) {
for (int i = 0; i < arr.size(); ++i) {
if (arr[i] == numToSearchFor) {
return i;
}
}
return -1;
}
std::tuple<int, int> linearSearch(std::vector<std::vector<int>> arr, int numToSearchFor) {
for (int i = 0; i < arr.size(); ++i) {
int columnLocation = linearSearch(arr[i], numToSearchFor);
if (columnLocation > -1) {
return {i, columnLocation};
}
}
return {-1, -1};
}