Open In App

Sentinel Linear Search

Improve
Improve
Like Article
Like
Save
Share
Report

Sentinel Linear Search as the name suggests is a type of Linear Search where the number of comparisons is reduced as compared to a traditional linear search. In a traditional linear search, only N comparisons are made, and in a Sentinel Linear Search, the sentinel value is used to avoid any out-of-bounds comparisons, but there is no additional comparison made specifically for the index of the element being searched.
In this search, the last element of the array is replaced with the element to be searched and then the linear search is performed on the array without checking whether the current index is inside the index range of the array or not because the element to be searched will definitely be found inside the array even if it was not present in the original array since the last element got replaced with it. So, the index to be checked will never be out of the bounds of the array. The number of comparisons in the worst case there will be (N + 2).

Sentinel linear search is a variation of the standard linear search algorithm used to find a target value in an array or list. The basic idea behind this algorithm is to add a sentinel value at the end of the array which is equal to the target value we are looking for. This helps to avoid checking the array boundary condition during each iteration of the loop, as the sentinel value acts as a stopper for the loop.

Although in worst-case time complexity both algorithms are O(n). Only the number of comparisons are less in sentinel linear search than linear search

Use of the Sentinel Linear Search :

In the context of searching for an element in an array, Sentinel Linear Search is a variant of Linear Search algorithm that uses a sentinel value to optimize the search process.

The basic idea of Sentinel Linear Search is to add an extra element at the end of the array (i.e., the sentinel value) that matches the search key. By doing so, we can avoid the conditional check for the end of the array in the loop and terminate the search early, as soon as we find the sentinel element. This eliminates the need for a separate check for the end of the array, resulting in a slight improvement in the average case performance of the algorithm.

Here are the steps for Sentinel Linear Search algorithm:

  • Initialize the search index variable i to 0.
  • Set the last element of the array to the search key.
  • While the search key is not equal to the current element of the array (i.e., arr[i]), increment the search index i.
  • If i is less than the size of the array or arr[i] is equal to the search key, return the value of i (i.e., the index of the search key in the array).
  • Otherwise, the search key is not present in the array, so return -1 (or any other appropriate value to indicate that the key is not found).

The key benefit of the Sentinel Linear Search algorithm is that it eliminates the need for a separate check for the end of the array, which can improve the average case performance of the algorithm. However, it does not improve the worst-case performance, which is still O(n) (where n is the size of the array), as we may need to scan the entire array to find the sentinel value.
Examples: 

Input: arr[] = {10, 20, 180, 30, 60, 50, 110, 100, 70}, x = 180 
Output: 180 is present at index 2
Input: arr[] = {10, 20, 180, 30, 60, 50, 110, 100, 70}, x = 90 
Output: Not found 

Below is the implementation of the above approach:  

C++




// C++ implementation of the approach
#include <iostream>
using namespace std;
 
// Function to search x in the given array
void sentinelSearch(int arr[], int n, int key)
{
 
    // Last element of the array
    int last = arr[n - 1];
 
    // Element to be searched is
    // placed at the last index
    arr[n - 1] = key;
    int i = 0;
 
    while (arr[i] != key)
        i++;
 
    // Put the last element back
    arr[n - 1] = last;
 
    if ((i < n - 1) || (arr[n - 1] == key))
        cout << key << " is present at index " << i;
    else
        cout << "Element Not found";
}
 
// Driver code
int main()
{
    int arr[] = { 10, 20, 180, 30, 60, 50, 110, 100, 70 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int key = 180;
 
    sentinelSearch(arr, n, key);
 
    return 0;
}
// This code is contributed by Mandeep Dalavi


Java




// Java implementation of the approach
class GFG {
 
    // Function to search x in the given array
    static void sentinelSearch(int arr[], int n, int key)
    {
 
        // Last element of the array
        int last = arr[n - 1];
 
        // Element to be searched is
        // placed at the last index
        arr[n - 1] = key;
        int i = 0;
 
        while (arr[i] != key)
            i++;
 
        // Put the last element back
        arr[n - 1] = last;
 
        if ((i < n - 1) || (arr[n - 1] == key))
            System.out.println(key + " is present at index "
                               + i);
        else
            System.out.println("Element Not found");
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[]
            = { 10, 20, 180, 30, 60, 50, 110, 100, 70 };
        int n = arr.length;
        int key = 180;
 
        sentinelSearch(arr, n, key);
    }
}
 
// This code is contributed by Ankit Rai, Mandeep Dalavi


Python3




# Python3 implementation of the approach
# Function to search key in the given array
 
 
def sentinelSearch(arr, n, key):
 
    # Last element of the array
    last = arr[n - 1]
 
    # Element to be searched is
    # placed at the last index
    arr[n - 1] = key
    i = 0
 
    while (arr[i] != key):
        i += 1
 
    # Put the last element back
    arr[n - 1] = last
 
    if ((i < n - 1) or (arr[n - 1] == key)):
        print(key, "is present at index", i)
    else:
        print("Element Not found")
 
 
# Driver code
arr = [10, 20, 180, 30, 60, 50, 110, 100, 70]
n = len(arr)
key = 180
 
sentinelSearch(arr, n, key)
 
# This code is contributed by divyamohan123, Mandeep Dalavi


C#




// C# implementation of the approach
using System;
 
class GFG {
 
    // Function to search x in the given array
    static void sentinelSearch(int[] arr, int n, int key)
    {
 
        // Last element of the array
        int last = arr[n - 1];
 
        // Element to be searched is
        // placed at the last index
        arr[n - 1] = key;
        int i = 0;
 
        while (arr[i] != key)
            i++;
 
        // Put the last element back
        arr[n - 1] = last;
 
        if ((i < n - 1) || (arr[n - 1] == key))
            Console.WriteLine(key + " is present"
                              + " at index " + i);
        else
            Console.WriteLine("Element Not found");
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr
            = { 10, 20, 180, 30, 60, 50, 110, 100, 70 };
        int n = arr.Length;
        int key = 180;
 
        sentinelSearch(arr, n, key);
    }
}
 
// This code is contributed by Mohit kumar, Mandeep Dalavi


Javascript




<script>
// javascript implementation of the approach   
// Function to search x in the given array
    function sentinelSearch(arr , n , key) {
 
        // Last element of the array
        var last = arr[n - 1];
 
        // Element to be searched is
        // placed at the last index
        arr[n - 1] = key;
        var i = 0;
 
        while (arr[i] != key)
            i++;
 
        // Put the last element back
        arr[n - 1] = last;
 
        if ((i < n - 1) || (arr[n - 1] == key))
            document.write(key + " is present at index " + i);
        else
            document.write("Element Not found");
    }
 
    // Driver code
     
        var arr = [ 10, 20, 180, 30, 60, 50, 110, 100, 70 ];
        var n = arr.length;
        var key = 180;
 
        sentinelSearch(arr, n, key);
 
// This code is contributed by todaysgaurav
</script>


Output

180 is present at index 2

Time Complexity: O(N)
Auxiliary Space: O(1)

Method 2 :

Here are the steps involved in the Sentinel Linear Search Algorithm:

  1. Set the last element of the array to the target value. This is known as the sentinel value.
  2. Set the index variable “i” to the first element of the array.
  3. Use a loop to iterate through the array, comparing each element with the target value.
  4. If the current element is equal to the target value, return the index of the current element.
  5. Increment the index variable “i” by 1 after each iteration of the loop.
  6. If the loop completes and the target value is not found, return -1 to indicate that the value is not present in the array.

The sentinel linear search algorithm is useful for arrays with a large number of elements where the target value may be located towards the end of the array. By adding the sentinel value at the end of the array, we can eliminate the need to check the array boundary condition during each iteration of the loop, thereby reducing the overall running time of the algorithm.

C++




#include <iostream>
#include <vector>
 
int sentinelLinearSearch(std::vector<int> array, int key) {
    int last = array[array.size() - 1];
    array[array.size() - 1] = key;
    int i = 0;
    while (array[i] != key) {
        i++;
    }
    array[array.size() - 1] = last;
    if (i < array.size() - 1 || last == key) {
        return i;
    } else {
        return -1;
    }
}
 
int main() {
    std::vector<int> array = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int key = 5;
    int index = sentinelLinearSearch(array, key);
    if (index == -1) {
        std::cout << key << " is not found in the array." << std::endl;
    } else {
        std::cout << key << " is found at index " << index << " in the array." << std::endl;
    }
    return 0;
}


Java




import java.util.Arrays;
 
public class SentinelLinearSearch {
    public static int sentinelLinearSearch(int[] array, int key) {
        int last = array[array.length - 1];
        array[array.length - 1] = key;
        int i = 0;
        while (array[i] != key) {
            i++;
        }
        array[array.length - 1] = last;
        if (i < array.length - 1 || last == key) {
            return i;
        } else {
            return -1;
        }
    }
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int key = 5;
        int index = sentinelLinearSearch(array, key);
        if (index == -1) {
            System.out.println(key + " is not found in the array: " + Arrays.toString(array));
        } else {
            System.out.println(key + " is found at index " + index + " in the array: " + Arrays.toString(array));
        }
    }
}


Python3




def sentinelLinearSearch(array, key):
    last = array[len(array) - 1]
    array[len(array) - 1] = key
    i = 0
    while array[i] != key:
        i += 1
    array[len(array) - 1] = last
    if i < len(array) - 1 or last == key:
        return i
    else:
        return -1
 
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
key = 5
index = sentinelLinearSearch(array, key)
if index == -1:
    print(f"{key} is not found in the array: {array}")
else:
    print(f"{key} is found at index {index} in the array: {array}")


C#




using System;
using System.Collections.Generic;
 
class MainClass {
    static int SentinelLinearSearch(List<int> array, int key) {
        int last = array[array.Count - 1];
        array[array.Count - 1] = key;
        int i = 0;
        while (array[i] != key) {
            i++;
        }
        array[array.Count - 1] = last;
        if (i < array.Count - 1 || last == key) {
            return i;
        } else {
            return -1;
        }
    }
 
    static void Main() {
        List<int> array = new List<int> {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int key = 5;
        int index = SentinelLinearSearch(array, key);
        if (index == -1) {
            Console.WriteLine(key + " is not found in the array.");
        } else {
            Console.WriteLine(key + " is found at index " + index + " in the array.");
        }
    }
}
//this code is contributed by snehalsalokhe


Javascript




// JavaScript
 
// Function to search key in given array
function sentinelLinearSearch(array, key)
{
 
    // Store the last element of the array
    let last = array[array.length - 1];
     
    // Replace the last element of the array with the key value
    array[array.length - 1] = key;
     
    // Initialize the index
    let i = 0;
     
    // Check if the array element is equal to the key
    while (array[i] !== key) {
        i++;
    }
     
    // Replace the last element of the array with the stored last element
    array[array.length - 1] = last;
     
    // Check if the key is found in the array
    if (i < array.length - 1 || last == key) {
        return i;
    } else {
        return -1;
    }
}
 
// Array of numbers
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
 
// Key to be searched
let key = 5;
 
// Find index of the key in the array
let index = sentinelLinearSearch(array, key);
 
// Print result
if (index == -1) {
    console.log(`${key} is not found in the array: ${array}`)
} else {
    console.log(`${key} is found at index ${index} in the array: ${array}`)
}


Output

5 is found at index 4 in the array: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Time Complexity :

The time complexity of the Sentinel Linear Search algorithm is O(n) in the worst case.

In the best case, when the key is found in the first iteration, the time complexity will be O(1).

However, the average time complexity is still O(n), because on average, the key will be found after



Last Updated : 09 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads