Open In App

Is Sentinel Linear Search better than normal Linear Search?

Last Updated : 23 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 linear search. When a linear search is performed on an array of size N then in the worst case a total of N comparisons are made when the element to be searched is compared to all the elements of the array and (N + 1) comparisons are made for the index of the element to be compared so that the index is not out of bounds of the array which can be reduced in a Sentinel Linear Search. So total comparisons in the worst case can be 2*N + 1.

But 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. 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).

Implementations:

See below the implementations of both the searching algorithm:

Implementation of Linear Search:

C++




// C++ code for traditional linear search
 
#include <bits/stdc++.h>
using namespace std;
 
// Function for linear search
int linearSearch(int arr[], int N, int x)
{
    for (int i = 0; i < N; i++)
        if (arr[i] == x)
            return i;
    return -1;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 3, 4, 10, 40 };
    int x = 10;
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    int result = linearSearch(arr, N, x);
    if (result == -1)
        cout << "Element not present";
    else
        cout << "Element present at index " << result;
 
    return 0;
}


Java




// Java code for traditional linear search
import java.io.*;
 
class GFG {
 
    // Function for linear search
    static int linearSearch(int[] arr, int N, int X)
    {
        for (int i = 0; i < N; i++) {
            if (arr[i] == X) {
                return i;
            }
        }
        return -1;
    }
 
    public static void main(String[] args)
    {
        int[] arr = { 2, 3, 4, 10, 40 };
        int x = 10;
        int N = arr.length;
 
        // Function call
        int result = linearSearch(arr, N, x);
        if (result == -1) {
            System.out.print("Element not present");
        }
        else {
            System.out.print("Element present at index "
                             + result);
        }
    }
}
 
// This code is contributed by lokesh


Python3




# Python code for traditional linear search
 
# Function for linear search
def linearSearch(arr, N, x):
    for i in range(N):
        if (arr[i] == x):
            return i
    return -1
 
# Driver code
if __name__ == "__main__":
    arr = [ 2, 3, 4, 10, 40 ]
    x = 10
    N = len(arr)
 
    # Function call
    result = linearSearch(arr, N, x)
    if (result == -1):
        print("Element not present")
    else:
        print("Element present at index",result)
 
# This code is contributed by Abhishek Thakur.


C#




// C# implementation of Sentinel Linear Search
 
using System;
 
public class GFG {
 
    // Function for linear search
    static int linearSearch(int[] arr, int N, int X)
    {
        for (int i = 0; i < N; i++) {
            if (arr[i] == X) {
                return i;
            }
        }
        return -1;
    }
 
    static public void Main()
    {
 
        // Code
        int[] arr = { 2, 3, 4, 10, 40 };
        int x = 10;
        int N = arr.Length;
 
        // Function call
        int result = linearSearch(arr, N, x);
        if (result == -1) {
            Console.Write("Element not present");
        }
        else {
            Console.Write("Element present at index "
                          + result);
        }
    }
}


Javascript




// JS code for traditional linear search
 
// Function for linear search
function linearSearch(arr, N, x)
{
    for (let i = 0; i < N; i++)
        if (arr[i] == x)
            return i;
    return -1;
}
 
// Driver code
let arr = [ 2, 3, 4, 10, 40 ];
let x = 10;
let N = arr.length;
 
// Function call
let result = linearSearch(arr, N, x);
if (result == -1)
    console.log("Element not present");
else
    console.log("Element present at index ", result);
     
// This code is contributed by akashish__


Output

Element present at index 3

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

Implementation of Sentinel Linear Search:

Below are the steps to implement the algorithm:

  • In sentinel search, we first insert the target element at the end of the list, and after that we compare each item of the list until we find our required item.
    • Either the required item is in the list, in that case it will be found before we reach the end of the list. 
    • Or the list didn’t have the target element, so the algorithm will reach the end of the list and find the target element that we have inserted initially.
  • Here, we have to do only one comparison, we only need to check if the element matches the target item or not, and we don’t need to check if we go out of the list.
  • Finally, check if the item we found was already there in the list or was added by us at the end of the list.
  • This check will happen only one time after the end of the loop.

Below is the code to implement the steps.

C++




// C++ implementation of Sentinel Linear Search
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to search Key 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 << "Element present at index " << i;
    else
        cout << "Element not present";
}
 
// Driver code
int main()
{
    int arr[] = { 2, 3, 4, 10, 40 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int key = 10;
 
    // Function call
    sentinelSearch(arr, N, key);
 
    return 0;
}


Java




// Java code for traditional linear search
import java.io.*;
 
class GFG {
 
    // Function for linear search
    static void linearSearch(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.print("Element present at index "
                             + i);
        else
            System.out.print("Element not present");
    }
 
    public static void main(String[] args)
    {
        int[] arr = { 2, 3, 4, 10, 40 };
        int key = 10;
        int N = arr.length;
 
        // Function call
        linearSearch(arr, N, key);
         
    }
}
 
// This code is contributed by Abhishek Sharma


Python3




# Python implementation of Sentinel Linear Search
 
# Function to search x 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=i+1
 
    # Put the last element back
    arr[n - 1] = last
 
    if ((i < n - 1) or (arr[n - 1] == key)):
        print("Element present at index",i)
    else:
        print("Element not present")
 
 
# Driver Code
if __name__ == "__main__":
 
    arr = [ 2, 3, 4, 10, 40 ]
    N = len(arr)
    key = 10
     
    # Function call
    sentinelSearch(arr, N, key)
 
 
# This code is contributed by Ayantika Dhuya(Tika).


C#




using System;
 
public class GFG {
 
  // C# implementation of Sentinel Linear Search
 
  // Function to search x in the given array
  public 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("Element present at index "
                        + i);
    else
      Console.WriteLine("Element not present");
  }
 
  // Driver code
  static public void Main()
  {
 
    int[] arr = { 2, 3, 4, 10, 40 };
    int N = arr.Length;
    int key = 10;
 
    // Function call
    sentinelSearch(arr, N, key);
  }
}
 
// This code is contributed by akashish__


Javascript




// JS implementation of Sentinel Linear Search
 
// Function to search x in the given array
function sentinelSearch(arr, n, key)
{
    // Last element of the array
    let last = arr[n - 1];
 
    // Element to be searched is
    // placed at the last index
    arr[n - 1] = key;
    let 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.log("Element present at index ", i);
    else
        console.log("Element not present");
}
 
// Driver code
let arr = [ 2, 3, 4, 10, 40 ];
let N = arr.length;
let key = 10;
 
// Function call
sentinelSearch(arr, N, key);
 
// This code is contributed by akashish__


Output

Element present at index 3

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

Conclusion:

In Sentinel Linear Search, we are doing one less comparison in each step. So the time complexity is remarkably cut down. As mentioned earlier, we can see that in the worst case a traditional linear search utilizes 2*N+1 comparisons whereas the Sentinel linear search performs only N+2 comparisons.

So we can conclude that Sentinel Linear Search is better than normal Linear Search.



Previous Article
Next Article

Similar Reads

Sentinel Linear Search
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 comp
12 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
Multiple Linear Regression Model with Normal Equation
Prerequisite: NumPy Consider a data set, area (x1)rooms (x2)age (x3)price (y)2338656215274569244968972954756231768234253107485 let us consider, Here area, rooms, age are features / independent variables and price is the target / dependent variable. As we know the hypothesis for multiple linear regression is given by: [Tex]$h_{\theta}(x)=\theta_{0}
3 min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Why Arrays have better cache locality than Linked list?
What is a Cache locality?Cache locality refers to the property of computer programs where they tend to access a small, specific set of data repeatedly in a short period of time. By keeping this frequently accessed data in a small, fast memory region called a cache, the program can speed up its execution time. This is because accessing data from the
9 min read
Why quicksort is better than mergesort ?
This a common question asked in DS interviews that despite of better worst case performance of mergesort, quicksort is considered better than mergesort. There are certain reasons due to which quicksort is better especially in case of arrays: Auxiliary Space : Mergesort uses extra space, quicksort requires little space and exhibits good cache locali
2 min read
Is Comb Sort better than Bubble Sort?
Comb sort and bubble sort are both simple sorting algorithms that are easy to implement. However, comb sort is generally considered to be more efficient than bubble sort. How Comb Sort WorksComb sort works by repeatedly comparing adjacent elements in the array and swapping them if they are out of order. The gap between the compared elements is init
2 min read
Length of longest subarray in which elements greater than K are more than elements not greater than K
Given an array arr[] of length N. The task is to find the length of the longest subarray in which elements greater than a given number K are more than elements not greater than K.Examples: Input : N = 5, K = 2, arr[]={ 1, 2, 3, 4, 1 } Output : 3 The subarray [2, 3, 4] or [3, 4, 1] satisfy the given condition, and there is no subarray of length 4 or
10 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
Practice Tags :
three90RightbarBannerImg