Linear Search with Sentinel
#include <vector> #include <iostream> #include <limits> // Helper function to perform linear search with a sentinel int linearSearchSentinelHelper(const std::vector<int>& arr, int target) { // Create a temporary vector with the target appended as a sentinel // This avoids modifyi...
This C++ code implements a linear search algorithm using a sentinel value. The sentinel is an extra element appended to the array (or a copy of it) that is guaranteed to match the target value. This simplifies the loop c...
The `linearSearchSentinel` function utilizes a sentinel value to simplify the linear search process. It creates a temporary copy of the input array `arr` and appends the `target` value to this copy, effectively making the `target` the sentinel. The `linearSearchSentinelHelper` then iterates through this augmented array using a single `while` loop condition: `tempArr[i] != target`. This loop is guaranteed to terminate because the `target` is present at least once (as the sentinel). After the loop, it checks if the index `i` is less than `n - 1` (where `n` is the size of the augmented array). If `i < n - 1`, it means the `target` was found within the original portion of the array, and its index `i` is returned. Otherwise, if `i == n - 1`, it implies that the `target` was only found at the sentinel position, meaning it was not present in the original array, and -1 is returned. The time complexity is O(n) in the worst case, where n is the size of the original array, as it might need to scan through all elements plus the sentinel. The space complexity is O(n) due to the creation of a temporary copy of the array. This approach is a variation of linear search that can sometimes offer minor performance improvements by simplifying loop logic, especially in languages where array bounds checking is expensive.
function linearSearchSentinel(array, target): if array is empty: return -1 // Create a temporary array with the target appended as a sentinel temp_array = copy of array append target to temp_array n = length of temp_arra...