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).
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 :
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.
Steps in Sentinel Linear Search
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++
#include <iostream>
#include <vector>
using namespace std;
// Function to search x in the given vector
int sentinelSearch(vector<int>& arr, int key) {
// Last element of the vector
int last = arr.back();
// Element to be searched is placed at the last index
arr.back() = key;
int i = 0;
while (arr[i] != key)
i++;
// Put the last element back
arr.back() = last;
// Return the index if found, otherwise return -1
if ((i < arr.size() - 1) || (arr.back() == key))
return i;
else
return -1;
}
int main() {
vector<int> arr = { 10, 20, 180, 30, 60, 50, 110, 100, 70 };
int key = 180;
int result = sentinelSearch(arr, key);
if (result != -1)
cout << key << " is present at index " << result;
else
cout << "Element not found";
return 0;
}
C
#include <stdio.h>
// Function to search key in the given array
int 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;
// Loop to find the element
while (arr[i] != key)
i++;
// Put the last element back
arr[n - 1] = last;
// Return the index if found, otherwise return -1
if ((i < n - 1) || (arr[n - 1] == key))
return i;
else
return -1;
}
int main() {
int arr[] = {10, 20, 180, 30, 60, 50, 110, 100, 70};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 180;
int result = sentinelSearch(arr, n, key);
if (result != -1)
printf("%d is present at index %d\n", key, result);
else
printf("Element not found\n");
return 0;
}
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
Python
# 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>
Output180 is present at index 2
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem