Working of Sentinal Linear Search in C++
Here’s a step-by-step example to understand the working of Sentinel Linear Search.
Input
Array of elements: [1, 8, 4, 11, 6] Target element to search for: 4
- Append the target element (8) at the end of the array as a sentinel. Array becomes: [3, 5, 1, 8, 2, 8]
- Initialize a loop variable i to 0, representing the current index.
- Compare the element at index 0 with the target element (8). No match (3 ≠ 8).
- Increment the loop variable i to 1 and compare the element at index 1 with the target element (8). No match (5 ≠ 8).
- Increment the loop variable i to 2 and compare the element at index 2 with the target element (8). No match (1 ≠ 8).
- Increment the loop variable i to 3 and compare the element at index 3 with the target element (8). A match is found (8 = 8).
- The search is successful, and the index (3) where the match was found is returned.
Output
The target element 8 is found at index 3 in the original array.
C++ Program For Sentinel Linear Search
The Sentinal linear search is a version of linear search where the last element of the array is replaced by a value to be searched. This helps in reducing the number of comparisons made to check for array boundaries and hence, improving the performance. In this article, we will discuss the sentinal linear search, it’s working, and how to implement it in C++. We will also look at the performance comparison of sentinal linear search vs traditional linear search.