Open In App

C++ Program For Sentinel Linear Search

Last Updated : 26 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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
  1. Append the target element (8) at the end of the array as a sentinel. Array becomes: [3, 5, 1, 8, 2, 8]
  2. Initialize a loop variable i to 0, representing the current index.
  3. Compare the element at index 0 with the target element (8). No match (3 ≠ 8).
  4. Increment the loop variable i to 1 and compare the element at index 1 with the target element (8). No match (5 ≠ 8).
  5. Increment the loop variable i to 2 and compare the element at index 2 with the target element (8). No match (1 ≠ 8).
  6. 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).
  7. The search is successful, and the index (3) where the match was found is returned.
cpp program for sentinal linear search

 

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;
}


Output

Element 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;
}


Output

Time 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;
}


Output

Time 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/



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads