C++ Program For Sentinel Linear Search
Last Updated :
26 Sep, 2023
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.
What is Sentinel Linear Search?
In traditional linear search, we compare each element of the array with the value to be searched. We do that using a loop that iterates from the first element of the array to the last element and in each iteration, the bound of the array is checked using a condition.
Sentinel Linear Search is a smarter way to make this process a bit faster. Instead of checking boundary conditions, you place a special "marker" number at the end of the list, and this marker is set to the number you're trying to find.
So, you start at the beginning as usual, but because you have this marker at the end, you don't need to keep checking if you've reached the end of the list. You know that as long as you keep looking, you will eventually find that marker number because it's always at the end. This simple trick reduces the number of comparisons you need to make because you're guaranteed to find the marker (which is also your target number) at some point.
Although the time complexity remains the same for both, the sentinel linear search is faster as it reduces the number of comparisons you need to make in each step.
Prerequisites: Before implementing Sentinel Linear Search in C++, you should have a basic understanding of:
- C++ programming language fundamentals.
- Arrays in C++.
- Basic knowledge of loops and conditionals.
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
Below is the implementation of the above approach:
C++
// C++ Program to implement Sentinel Linear Search
#include <iostream>
using namespace std;
int sentinelLinearSearch(int arr[], int size, int target)
{
// Store the last element as the sentinel
int last = arr[size - 1];
// Set the sentinel to the target
arr[size - 1] = target;
int i = 0;
while (arr[i] != target) {
i++;
}
// Restore the original value at the end
arr[size - 1] = last;
if (i < size - 1 || arr[size - 1] == target) {
return i; // Element found at index i
}
else {
return -1; // Element not found
}
}
// Driver code
int main()
{
int arr[] = { 1, 8, 4, 11, 2 };
int size = sizeof(arr) / sizeof(arr[0]);
int target = 4;
int result = sentinelLinearSearch(arr, size, target);
// printing result if the based on the value returned by
// sentinalLiner Search
if (result != -1) {
cout << "Element " << target << " found at index "
<< result << endl;
}
else {
cout << "Element " << target << " not found"
<< endl;
}
return 0;
}
OutputElement 4 found at index 2
Time Complexity: O(N)
Auxiliary Space: O(1)
Sentinel Linear Search Vs Traditional Linear Search
The following table lists some of the main differences between Sentinel Linear Search and Traditional linear search:
Sentinel Linear Search
| Traditional Linear Search
|
---|
In a sentinel linear search, you add a sentinel (a special value) at the end of the list, which acts as a marker for the end of the search. | In traditional linear search, you start from the beginning of the list and go through each element one by one until you find the target item or reach the end of the list. |
Instead of explicitly comparing each element with the target value, you start by comparing the target value with the sentinel at the end of the list. This eliminates the need for a comparison in the loop. | You explicitly compare each element in the list with the target value, and if there's a match, you stop the search. |
Sentinel search is optimized because it reduces the number of comparisons. | There is no such optimization in traditional linear search. |
Performance Comparision of Sentinel Linear Search
Let's take an example that calculates the execution time of a sentinal linear search on a big dataset.
Sentinel Linear Search
C++
// C++ program to find the execution time of sentinal linear search
#include <ctime>
#include <iostream>
#define ARRAY_SIZE 1000000
#define TARGET_VALUE 999999
// Sentinel Linear Search
int sentinelSearch(int arr[], int size, int target)
{
int lastValue = arr[size - 1];
arr[size - 1] = target;
int i = 0;
while (arr[i] != target) {
i++;
}
arr[size - 1] = lastValue;
if (i < size - 1 || arr[size - 1] == target) {
return i; // Found the target value at index i
}
else {
return -1; // Target value not found in the array
}
}
// driver code
int main()
{
int arr[ARRAY_SIZE];
// Initialize the array with sorted values from 0 to
// ARRAY_SIZE - 1
for (int i = 0; i < ARRAY_SIZE; i++) {
arr[i] = i;
}
int target = TARGET_VALUE;
// Measure the execution time
clock_t start_time, end_time;
start_time = clock();
// Perform the sentinel search
int result = sentinelSearch(arr, ARRAY_SIZE, target);
end_time = clock();
// Calculate the execution time in seconds
double execution_time
= ((double)(end_time - start_time))
/ CLOCKS_PER_SEC;
// Print the execution time
std::cout << "Time taken by sentinel Search: "
<< execution_time << " seconds" << std::endl;
return 0;
}
OutputTime taken by sentinel Search: 0.002236 seconds
Traditional Linear Search
Let's search the same dataset with a linear search.
C++
// C++ program to check the execution time of tratitional
// linear search
#include <ctime>
#include <iostream>
#define ARRAY_SIZE 1000000
#define TARGET_VALUE 999999
// Traditional Linear Search
int linearSearch(int arr[], int size, int target)
{
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
// driver code
int main()
{
int arr[ARRAY_SIZE];
// Initialize the array with sorted values from 0 to
// ARRAY_SIZE - 1
for (int i = 0; i < ARRAY_SIZE; i++) {
arr[i] = i;
}
int target = TARGET_VALUE;
// Measure the execution time
clock_t start_time, end_time;
start_time = clock();
// Perform the linear search
int result = linearSearch(arr, ARRAY_SIZE, target);
end_time = clock();
// Calculate the execution time in seconds
double execution_time
= ((double)(end_time - start_time))
/ CLOCKS_PER_SEC;
// Print the execution time
std::cout << "Time taken by linear Search: "
<< execution_time << " seconds" << std::endl;
return 0;
}
OutputTime taken by linear Search: 0.002409 seconds
Although the sentinel linear search is faster, the difference is very small. This is one of the reasons why the sentinel linear search is not commonly used. The other reasons are the dataset mutability requirements and unexpected errors in the shared environment.
For more details about Sentinel Linear Search, refer www.geeksforgeeks.org/sentinel-linear-search/
Similar Reads
C Program For Sentinel Linear Search
Sentinel Linear Search is basically a variation of the traditional linear search algorithm. It is designed to reduce the number of comparisons required to find a specific target value within an array or list. In this article, we will learn how to implement Sentinal Linear Search in C, see how it wor
8 min read
Sentinel Linear Search in Java
The Linear search is a simple searching algorithm that checks every element in the list or array sequentially until the target element is found or the end of the list is reached. While linear search is not the most efficient search algorithm it is straightforward and works well for small datasets or
3 min read
C++ Program For Iterative Quick Sort
Quicksort also known as partition-exchange sort is a divide-and-conquer sorting algorithm that works by selecting a pivot element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot element. The sub-arrays can then
4 min read
Is Sentinel Linear Search better than normal Linear Search?
Sentinel Linear search is a type of linear search where the element to be searched is placed in the last position and then all the indices are checked for the presence of the element without checking for the index out of bound case.The number of comparisons is reduced in this search as compared to a
8 min read
Output of C++ programs | Set 39 (Pointers)
Prerequisite: Pointers in C/C++ QUE.1 What would be printed from the following C++ program? CPP #include <iostream> #include <stdlib.h> using namespace std; int main() { float x = 5.999; float* y, *z; y = &x; z = y; cout << x << ", " << *(&x) <<
4 min read
C++ Libraries for Machine Learning
Machine learning (ML) has significantly transformed various industries by enabling systems to learn from data and make predictions. While Python is often the go-to language for ML due to its extensive libraries and ease of use, C++ is increasingly gaining attention for ML applications. C++ offers su
5 min read
C++ Tutorial | Learn C++ Programming
C++ is a popular programming language that was developed as an extension of the C programming language to include OOPs programming paradigm. Since then, it has become foundation of many modern technologies like game engines, web browsers, operating systems, financial systems, etc.Features of C++Why
5 min read
C++ Program for DFS Traversal
In C++ Depth-First Search (DFS) is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node and explores as far as possible along each branch before backtracking. In this article, we will learn how to implement DFS traversal in C++. Example: Input
3 min read
What is Linear Search?
Linear search is defined as the searching algorithm where the list or data set is traversed from one end to find the desired value. Linear search method Linear search works by sequentially checking each element in the list until the desired value is found or the end of the list is reached. Propertie
3 min read
Indexed Sequential Search
In this searching method, first of all, an index file is created, that contains some specific group or division of required record when the index is obtained, then the partial indexing takes less time cause it is located in a specified group. Note: When the user makes a request for specific records
7 min read