Open In App

Sentinel Linear Search

Last Updated : 09 May, 2023
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



Previous Article
Next Article

Similar Reads

Is Sentinel Linear Search better than normal Linear Search?
What is Sentinel 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 traditional line
9 min read
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
7 min read
Doubly Linked List using Sentinel Nodes
In the case of the simple doubly linked list, if we have to perform the insertion or deletion operation at the starting of the doubly linked list, end of the doubly linked list, or in between the starting and end nodes for each, we require to check different condition that makes the algorithm complex so to solve this problem we can use doubly linke
15+ min read
Linear Search vs Binary Search
Prerequisite: Linear SearchBinary SearchLINEAR SEARCH Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position of the current item. Otherwise, we will move to t
11 min read
Which is faster between binary search and linear search?
In computer science, search algorithms are used to locate a specific element within a data structure. Two commonly used search algorithms are binary search and linear search. Understanding their relative speeds is crucial for optimizing search operations. Let's compare the speed of Binary Search and Linear Search to determine which one is faster. B
2 min read
Difference Between Linear Search and Jump Search
Linear Search and Jump Search are two different techniques used to find an element in a list. Each algorithm has its own set of characteristics, advantages, and limitations, making them suitable for different scenarios. This article explores the key differences between Linear Search and Jump Search. What is Linear Search?Linear Search, also known a
3 min read
Difference between Linear and Non-linear Data Structures
Linear Data Structure: Data structure where data elements are arranged sequentially or linearly where each and every element is attached to its previous and next adjacent is called a linear data structure. In linear data structure, single level is involved. Therefore, we can traverse all the elements in single run only. Linear data structures are e
5 min read
Recursive Linear Search Algorithm
Linear Search is defined as a sequential search algorithm that starts at one end and goes through each element of a list until the desired element is found, otherwise the search continues till the end of the data set. How Linear Search Works? Linear search works by comparing each element of the data structure with the key to be found. To learn the
6 min read
Linear search using Multi-threading
Given a large file of integers, search for a particular element in it using multi-threading. Examples: Input : 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220Output :if key = 20Key element foundInput :1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220Output :if key = 202Key not presentPrerequisite : Multi-threading Recommen
6 min read
Number of comparisons in each direction for m queries in linear search
Given an array containing N distinct elements. There are M queries, each containing an integer X and asking for the index of X in the array. For each query, the task is to perform linear search X from left to right and count the number of comparisons it took to find X and do the same thing right to left. In the end, print the total number of compar
7 min read