Searches for the key by scanning one element after another.
template <typename T>
int sequentialSearch(const std::vector<T>& arr, const T& target) {
for (int i = 0; i < arr.size(); ++i) {
if (arr[i] == target) {
return i; // Return the index if target is found
}
}
return -1; // Return -1 if target is not found
}
Source code: sequential_search.cpp
It will be used in sorted lists by the search key, this is the best method.
key < a[middle]: Search between lower and middle–1key > a[middle]: Search between middle+1 and higherint binarySearch(const std::vector<T>& arr, const T& target) {
int low = 0;
int high = arr.size() - 1;
while (low <= high) {
int mid = low + (high - low) / 2; // Avoids potential overflow compared to (low + high) / 2
if (arr[mid] == target) {
return mid; // Target found
} else if (arr[mid] < target) {
low = mid + 1; // Search in the right half
} else {
high = mid - 1; // Search in the left half
}
}
return -1; // Target not found
}
Source Code: binary_search.cpp
int binarySearch(vector<int> &arr, int low, int high, int x) {
if (high >= low) {
int mid = low + (high - low) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, low, mid - 1, x);
return binarySearch(arr, mid + 1, high, x);
}
return -1;
}
Question: Would it work? What would be its complexity in the binary_serach.cpp file
Write one program that will be able to sort float, int and string arrays. Arrays will come from a user-provided file. Consider that you will need to sort it, if the users chooses the binary search.
Below you can see how your program will be run:
./main --input data.txt --binary-search./main --input data.txt --recursive-binary-search./main --input data.txt --sequential-searchAt the end, compare your running time with the grep program.
This material is genereated thanks to some extracts from following resources:
AI Overview