Javatpoint Logo
Javatpoint Logo

C++ program for Sentinel Linear Search

In this article, we will discuss the C++ program for sentinel linear search with different approaches. But before discussing their implementations, we must know about the sentinel linear search in C++.

What is the Sentinel Linear Search?

The "sentinel linear search" is a variation of the linear search algorithm that uses a sentinel value to simplify the code. A sentinel is a special value placed at the end of the array, and it is chosen in such a way that it is guaranteed not to be a valid input. In the, context of searching, the sentinel value is set equal to the search key.

Approach-1: Sentinel Linear Search as a Function

The Sentinel Linear Search implemented as a function involves encapsulating the search logic within a standalone function. This Function takes the array to be searched, its size, and the key to be found as parameters. Here's a detailed explanation:

Example:

Output:

Element found at index 2

Explanation:

Parameters:

  • arr: The array to be searched.
  • size: The size of the array.
  • key: The key to be found.

Sentinel Initialization:

  • The Function sets the last element of the array to the search key. It effectively creates a sentinel value.

Search Loop:

  • The Function uses a while loop to iterate through the array until the sentinel value (key) is found.
  • The loop increments the index variable until arr[index] equals the sentinel value.

Result Handling:

  • If the index is less than size - 1, the key is found, and the function returns the index.
  • If the index is equal to size - 1, the key is not found, and -1 is returned.

Main Function:

Array Initialization:

  • An example array arr with values {10, 20, 30, 40, 50} is created.
  • The key to be searched is set to 30.

Function Call:

  • The sentinelLinearSearch Function is called with the array, its size, and the key.
  • The result is stored in the result variable.

Result Display:

  • Based on the result, the program prints whether the element is found or not.
  • If the result is not -1, it prints the index where the key is found; otherwise, it indicates that the element is not in the array.

Complexity Analysis:

Time Complexity:

The time complexity of the Sentinel Linear Search is determined by the number of iterations in the search loop. In the worst-case scenario, the loop iterates through the entire array until it finds the sentinel value (search key) or reaches the end. Therefore, the time complexity is O(n), where n is the size of the array.

Space Complexity:

The space complexity refers to the amount of additional memory used by the algorithm. In the provided code:

Space Complexity for Input (Array): O(n), where n is the size of the array. The array is the primary input to the algorithm, and its space complexity is directly proportional to its size.

Space Complexity for Variables: O(1). The space required for variables like index, key, and result is constant and does not depend on the size of the input array.

The space complexity of the entire algorithm is determined by the maximum amount of memory the algorithm needs to allocate. In this case, it is dominated by the size of the input array.

Approach-2: Using a Class

Leveraging a class for the implementation of Sentinel Linear Search affords the opportunity to encapsulate the search logic within a cohesive and object-oriented structure. In this paradigm, the intricacies of the search process are encapsulated within the constructs of a class, promoting modularity and maintainability. The following example elucidates the integration of Sentinel Linear Search within a class, showcasing a more structured and object-oriented approach.

Example:

Output:

Element found at index 3

Explanation:

Constructor:

The class has a constructor that is invoked upon instantiation. It takes an array (arr), its size (size), and the key to be found (key) as parameters.

Sentinel Initialization:

The constructor sets the last element of the array to the search key. This establishes the sentinel value.

Search Loop:

A for loop is used to iterate through the array until the sentinel value (key) is found.

The loop increments the index variable until arr[index] equals the sentinel value.

Result Handling:

  • The index where the key is found stored in the result variable.
  • The result is determined using a ternary operator, and the value is displayed

main Function:

Array Initialization:

An example array arr with values {10, 20, 30, 40, 50} is created.

The key to be searched is set to 30.

Class Instantiation:

An instance of the SentinelLinearSearch class is created by passing the array, its size, and the key to the constructor.

Complexity Analysis:

Time Complexity:

The time complexity of the Sentinel Linear Search is determined by the number of iterations in the search loop. In the worst-case scenario, the loop iterates through the entire array until it finds the sentinel value (search key) or reaches the end. Therefore, the time complexity is O(n), where n is the size of the array.

Space Complexity:

The space complexity refers to the amount of additional memory used by the algorithm.

Space Complexity for Input (Array): O(n), where n is the size of the array. The array is the primary input to the algorithm, and its space complexity is directly proportional to its size.

Space Complexity for Variables in the Class:

index: O(1) - A single variable to keep track of the index during the search.

result: O(1) - A single variable to store the final result.

key (in the constructor): O(1) - A single variable storing the key.

Space Complexity for Local Variables in main:

size: O(1) - A constant-size variable storing the size of the array.

arr: O(n) - The input array.

key: O(1) - The key to be searched.

The overall space complexity of the algorithm is dominated by the size of the input array, resulting in O(n) space complexity.

Approach 3: Using a do-while Loop

In this approach, we use a do-while loop to ensure that the loop body is executed at least once. This approach is useful if you want to ensure that the search logic is executed even when the array is empty.

Example:

Output:

Element found at index 0

Explanation:

Sentinel Linear Search Function:

  • The function sentinelLinearSearch takes three parameters: arr (the array to be searched), size (the size of the array), and key (the element to be found).
  • A sentinel value is set at the end of the array (arr[size - 1] = key), ensuring the termination condition for the search.
  • The Function initializes the index variable to 0.
  • After that, it enters a do-while loop, which always executes at least once. Within the loop, it checks if the element at the current index (arr[index]) is equal to the search key. If true, it returns the index, signifying that the key is found.
  • The loop increments the index, continuing the search until the sentinel value is encountered.

Main Function:

  • The main Function initializes an array arr with values {10, 20, 30, 40, 50} and sets the key to be searched (key = 30).
  • It is then calls the sentinelLinearSearch function, passing the array, its size, and the key.
  • The result is stored in the result variable.
  • Finally, the program displays whether the element is found or not based on the result.

Complexity Analysis:

Time Complexity:

The time complexity of the Sentinel Linear Search is determined by the number of iterations in the search loop. In this implementation:

  • The loop iterates through the array linearly until it finds the sentinel value (search key) or reaches the end.
  • In the worst-case scenario, the loop may iterate through the entire array.
  • Therefore, the time complexity is O(n), where n is the size of the array.

Space Complexity:

The space complexity refers to the amount of additional memory used by the algorithm.

Space Complexity for Input (Array): O(n), where n is the size of the array. The array is the primary input to the algorithm, and its space complexity is directly proportional to its size.

Space Complexity for Variables:

index: O(1) - A single variable to keep track of the index during the search.

key (parameter): O(1) - A single variable storing the key.

Space Complexity for Loop Condition:

  • The do-while loop condition does not require additional space beyond the loop control variable (index).
  • The overall space complexity of the algorithm is O(n) due to the size of the input array, which dominates the space requirements.

Approach 4: Recursive Implementation

Another approach is to use recursion for the search. This might not be the most efficient approach due to the potential for stack overflow for large arrays, but it showcases a different way of expressing the algorithm.

Example:

Output:

Element found at index 4

Explanation:

SentinelLinearSearchRecursive Function:

Parameters:

arr: The array to be searched.

index: The current index being checked.

size: The size of the array.

key: The key to be found in the array.

  • The Function sets the sentinel value at the end of the array (arr[size - 1] = key) to simplify the termination condition for the recursive calls.
  • Base Case: If the element at the current index is equal to the search key (arr[index] == key), the Function returns the index, signifying that the key is found.
  • Recursive Case: If the base case is not met, the function recursively calls itself with an incremented index, continuing the search.
  • The recursive call effectively iterates through the array until it either finds the key or reaches the end of the array.

main Function:

  • Initializes an array arr with values {10, 20, 30, 40, 50} and sets the key to be searched (key = 30).
  • Calls the sentinelLinearSearchRecursive function with the array, starting index (0), array size, and key.
  • Stores the result in the result variable.
  • Displays whether the element is found or not based on the result.

Complexity Analysis:

Time Complexity:

The time complexity of the recursive Sentinel Linear Search is determined by the number of recursive calls made until the base case is reached. In this implementation:

The Function makes recursive calls until the key is found or the end of the array is reached.

In the worst-case scenario, the algorithm may need to traverse the entire array.

Therefore, the time complexity is O(n), where n is the size of the array.

Space Complexity:

The space complexity refers to the amount of additional memory used by the algorithm.

Recursion Stack: O(n) - The space complexity is determined by the maximum depth of the recursion stack. In the worst case, the recursion stack will have a depth equal to the size of the array, as each recursive call adds a new frame to the stack.

Other Variables: O(1) - Additional variables (index, size, key) use constant space. These variables do not grow with the size of the input.

The overall space complexity is dominated by the recursion stack, resulting in O(n) space complexity.

Applications:

The Sentinel Linear Search algorithm finds its applications in various domains where the goal is to locate a specific element within a collection of data. Its simplicity and efficiency make it suitable for certain scenarios. Let's explore several applications of the Sentinel Linear Search in detail:

Database Management Systems:

In database management systems, Sentinel Linear Search can be utilized for searching records within databases. Consider a scenario where a database contains user information, and we need to determine if a particular user exists in the system. By employing the Sentinel Linear Search, the algorithm iterates through the user records until it finds a match or reaches the end of the database. This method is particularly applicable when the database not sorted, and a sequential search is necessary.

Text Processing and Parsing:

In text, processing applications, the Sentinel Linear Search can be employed to locate specific patterns or keywords within a text document. For instance, in a word processing program, the algorithm might be used to identify occurrences of a particular word or phrase in a document. The sentinel value ensures that the search continues until the end of the text is reached, allowing for a comprehensive examination of the content.

Information Retrieval Systems:

In information retrieval systems, where large datasets are indexed and searched for relevant information, the Sentinel Linear Search can play a role. For instance, in a document retrieval system, the algorithm can be used to determine if a specific keyword or document ID is present in the indexed collection. The simplicity of the Sentinel Linear Search makes it suitable for such applications where the data is not necessarily sorted or indexed.

Error Detection in Data Transmission:

In networking and communication systems, Sentinel Linear Search can be applied for error detection. By appending a sentinel value at the end of a transmitted data sequence, the receiver can use the search algorithm to ensure that the data has been accurately received. If the sentinel value is not found, it indicates a potential error or incomplete transmission, triggering appropriate error-handling mechanisms.

Conclusion:

The Sentinel Linear Search algorithm, while not the most efficient for large datasets, finds practical applications in scenarios where simplicity, ease of implementation, and sequential searching are acceptable. Its versatility makes it suitable for a range of applications, from database management to text processing, networking, educational systems, and game development. Understanding the strengths and limitations of the Sentinel Linear Search allows developers to choose the most appropriate algorithm for specific use cases, optimizing performance and achieving desired outcomes.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA