Two Way Linear Search Algorithm In C++ - C++ Programming Tutorial
C++ Course / STL Algorithm / Two Way Linear Search Algorithm In C++

Two Way Linear Search Algorithm In C++

BLUF: Mastering Two Way Linear Search Algorithm In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Two Way Linear Search Algorithm In C++

C++ is renowned for its efficiency. Learn how Two Way Linear Search Algorithm In C++ enables low-level control and high-performance computing in the tutorial below.

In the field of computer science and programming, search algorithms play a vital role in enabling the extraction of information from different data structures. One notable example is the linear search algorithm, known for its uncomplicated nature and easy execution. It operates by inspecting each item in a sequence or collection one by one until it locates the desired value or reaches the end of the data set. This technique is straightforward and user-friendly, which is why it is favored by novices and in situations where simplicity outweighs efficiency. Nevertheless, as the size of datasets increases, the drawbacks of a basic linear search become more evident, necessitating the adoption of more efficient strategies.

An example of optimization includes the Two-Way Linear Search Algorithm. This version of the linear search method incorporates a smart strategy by searching from the beginning and end of the list towards the middle concurrently. The objective is to minimize the comparisons required to locate the desired element, ultimately enhancing search performance, particularly when the element is positioned close to the list's edges.

To comprehend the importance of this enhancement, it is beneficial to examine the time complexity of the linear search algorithm. In the most unfavorable scenario, a linear search operates with a time complexity of O(n), where n signifies the quantity of elements within the list. This is due to the necessity of inspecting each element before determining the absence of the desired target. Although this linear time complexity is satisfactory for smaller lists, it can pose limitations as the dataset expands. The bidirectional linear search maintains the O(n) complexity in the worst case but endeavors to enhance the average-case efficiency, which is frequently of greater significance in real-world applications.

The advantages of the two-way linear search extend beyond just its potential for decreasing comparisons. The method is straightforward to both implement and comprehend, similar to the fundamental linear search. It does not necessitate any extra memory apart from a few additional variables, thus upholding an O(1) auxiliary space complexity. This feature renders it appealing for scenarios with limited memory or where the additional complexity of other algorithms is unnecessary.

In real-world scenarios, the dual-directional linear search proves valuable when dealing with unsorted datasets, offering a compromise between straightforwardness and effectiveness. It is especially beneficial for educational objectives, acting as a transitional phase from the fundamental linear search to sophisticated search techniques like binary search or hash-based algorithms.

Nevertheless, it is crucial to understand that the bidirectional linear search method is not a cure-all solution. Its benefits are most evident when the desired element is located close to the beginning or end of the collection. If the target consistently resides towards the center, the enhancement over a basic linear search diminishes. Moreover, in scenarios involving large datasets where search speed is of utmost importance, more advanced techniques such as binary search (for ordered datasets) or hashing (for efficient retrievals) may be more suitable. This guide will provide a detailed examination of the mechanics behind the bidirectional linear search algorithm, including its application in C++, its strengths, and its constraints. By the conclusion, you will possess a thorough comprehension of how this algorithm functions and when it is the optimal choice for a particular task.

Basic Linear Search Overview

Linear search stands out as one of the most basic and direct search algorithms within the realm of computer science. This essential algorithm is employed to ascertain whether a specified element exists within a given list or array. Its methodology involves examining each element of the list in succession until the desired element is located or the list is fully traversed. Owing to its straightforward nature and simple implementation, linear search frequently serves as the initial search algorithm introduced in foundational computer science classes.

How does Linear Search Works?

The simple linear search procedure initiates from the start of the collection and examines each item against the desired value. Upon discovering a match, it provides the index of the matched item. In case it traverses the entire list without locating the target, it outputs a specific value (often -1) to signify the absence of the target within the list.

Here's a step-by-step breakdown of the linear search process:

  • Initialization: Start with the first element of the list.
  • Comparison: Compare the current element with the target value.
  • Match Check: If the current element matches the target, return the index of the current element. If the current element does not match the target, move to the next element.
  • Iteration: Repeat steps 2 and 3 until the end of the list is reached.
  • End of List: If the end of the list is reached without finding the target, return -1.
  • If the current element matches the target, return the index of the current element.
  • If the current element does not match the target, move to the next element.
  • Example of Linear Search in C++

Let's examine a basic example to demonstrate the linear search algorithm in C++:

Example

#include <iostream>
#include <vector>
int linearSearch(const std::vector<int>& arr, int target) {
    for (int i = 0; i < arr.size(); ++i) {
        if (arr[i] == target) {
            return i;  // Target found, return index
        }
    }
    return -1;  // Target not found
}

int main() {
    std::vector<int> data = {4, 2, 7, 1, 3, 9, 5};
    int target = 7;
    int result = linearSearch(data, target);

    if (result != -1) {
        std::cout << "Element found at index " << result << std::endl;
    } else {
        std::cout << "Element not found" << std::endl;
    }

    return 0;
}

Output:

Output

Element found at index 2

Explanation of the Code

  1. Function Definition:
  • The linearSearch function takes a std::vector<int> and an int target as parameters.
  • It iterates through the vector using a for loop.
  • Within the loop, it checks if the current element (arr[i]) matches the target.
  • If a match is found, it returns the index i.
  • If the loop completes without finding the target, it returns -1.
  1. Main Function:
  • The main function initializes a vector data with some integers.
  • It sets a target value to search for.
  • It calls linearSearch with data and target, storing the result in result.
  • Depending on the value of result, it prints whether the element was found and its index, or that the element was not found.

Time Complexity

The time complexity of the sequential search algorithm is represented as O(n), where n signifies the quantity of items in the list. This holds true because, at its worst, the algorithm might have to inspect each item in the list to ascertain the presence or absence of the target. Such linear time complexity signifies that the algorithm's execution time grows proportionally with the list's size.

Space Complexity

The linear search has a space complexity of O(1), indicating that it necessitates a consistent amount of extra space irrespective of the input list's size. This is due to the algorithm solely utilizing a small number of additional variables (such as the index counter and the target value) that do not increase along with the input's magnitude.

Effortlessness and Simple Integration

One of the most significant advantages of linear search is its simplicity. The algorithm is straightforward and easy to understand, making it an ideal choice for beginners and for use in educational contexts.

  • Minimal Learning Curve: Linear search is often the first search algorithm taught in introductory computer science courses because it requires minimal prior knowledge to understand and implement.
  • Readable Code: The implementation of linear search is concise and easy to read, which enhances code maintainability and reduces the likelihood of errors.
  • Quick Prototyping: For quick prototyping or when time constraints are a factor, the simplicity of linear search allows developers to implement a working search function rapidly.
  1. No Requirement for Sorted Data

Unlike more efficient search algorithms such as binary search, linear search does not require the data to be sorted. This characteristic makes linear search highly versatile and applicable to any dataset.

  • Unsorted Data: Linear search can be applied directly to unsorted lists, saving the overhead of sorting the data first.
  • Dynamic Data: In situations where data is frequently inserted or deleted, maintaining a sorted list can be cumbersome. Linear search handles such dynamic data efficiently without the need for re-sorting.
  1. Flexibility with Various Data Structures

Linear search is not restricted to arrays or lists; it can be used with any data structure that allows sequential access to its elements.

  • Arrays and Lists: Linear search works well with arrays and linked lists, making it a versatile tool in many programming contexts.
  • Custom Data Structures: It can be adapted to work with custom data structures where elements are accessed sequentially.
  1. Constant Space Complexity

The linear search algorithm operates with a constant space complexity of O(1), meaning it requires a fixed amount of additional memory regardless of the size of the input list.

  • Memory Efficiency: This makes linear search a suitable choice for memory-constrained environments where minimizing memory usage is critical.
  • Predictable Resource Usage: Developers can predict and control the memory consumption of their applications, ensuring that the search operation does not cause unexpected memory overhead.
  1. Guaranteed Performance

Linear search guarantees that it will find the target element if it exists in the list. This is in contrast to algorithms that may fail under certain conditions (e.g., binary search on unsorted data).

  • Deterministic Behavior: Linear search provides consistent and predictable performance, as it will always check each element exactly once.
  • No Pre-conditions: there are any pre-conditions for the data being searched, making linear search robust and reliable in various contexts.
  1. Suitable for Small Datasets

For small datasets, the performance difference between linear search and more complex algorithms is negligible. In these cases, the simplicity and ease of implementation of linear search often outweigh the benefits of more sophisticated methods.

  • Quick Execution: For small lists, the time taken to perform a linear search is minimal, making it an efficient choice.
  • Minimal Overhead: There is no overhead associated with preparing the data for search, such as sorting, which can be beneficial in scenarios where simplicity and speed are paramount.
  1. Adaptable to Different Data Types

Linear search can be used with various data types, including primitives, objects, and complex data structures. This adaptability makes it a valuable tool across different programming tasks .

  • Primitive Data Types: Linear search can efficiently handle searches in lists of integers, floating-point numbers, characters, etc.
  • Complex Data Structures: It can also be applied to lists of objects, where the search condition is based on specific attributes or properties of the objects.
  1. No Additional Data Structures Needed

Linear search does not require any additional data structures or preprocessing steps. This lack of dependencies simplifies the overall program design and reduces potential points of failure .

  • Straightforward Implementation: The lack of need for additional data structures means that the algorithm can be implemented quickly and with fewer dependencies .
  • Reduced Complexity: This also reduces the overall complexity of the software, making it easier to understand, maintain, and debug.
  1. Performance in Specific Scenarios

Linear search can outperform more complex algorithms in certain scenarios, particularly when the list is small or the target element is likely to be near the beginning of the list.

  • Small Lists: For small datasets, the overhead of more complex search algorithms might not justify their use. Linear search provides a quick and simple solution.
  • Early Matches: If the target element is expected to be near the beginning of the list, linear search can find it quickly without needing to traverse the entire list.
  1. Educational Value

Linear search acts as a valuable educational resource, exposing students to essential algorithm principles and aiding in their comprehension of search methodologies.

  • Building Block for Education: Grasping linear search sets the groundwork for comprehending advanced search algorithms and data structures.
  • Analyzing Algorithms: It enables students to hone their skills in evaluating algorithm efficiency, grasping ideas such as time complexity O(n) and space complexity O(1).

Challenges When Dealing with Extensive Data Sets

One of the most significant disadvantages of linear search is its inefficiency with large datasets. Linear search has a time complexity of O(n), where n is the number of elements in the list. This means that the algorithm must potentially examine every element in the list before finding the target, leading to poor performance as the size of the dataset increases.

  • Time Consuming: As the dataset grows, the time required to search for an element increases linearly. For very large datasets, this can lead to unacceptably long search times.
  • Scalability Issues: Linear search does not scale well with increasing data sizes. In contrast, more advanced algorithms like binary search, with O(logn) time complexity, can handle larger datasets more efficiently.
  1. Lack of Early Termination

Linear search does not have any mechanism for early termination based on partial information about the dataset. It continues to check each element until it either finds the target or reaches the end of the list.

  • No Advantage of Sorted Data: Unlike binary search, linear search cannot take advantage of sorted data to terminate early. Even if the data is sorted, linear search will still check every element.
  • Inefficiency in Best-Case Scenario: In the best-case scenario, where the target element is at the beginning of the list, linear search performs well. However, in average and worst-case scenarios, it lacks the efficiency of algorithms that can skip large portions of the list based on data properties.
  1. Higher Average and Worst-Case Time Complexity

The average and worst-case time complexities of linear search are both O(n). This high time complexity makes it unsuitable for performance-critical applications.

  • Average-Case Performance: On average, linear search requires n/2 comparisons, which is still a linear function of the dataset size. This can lead to slow performance, especially when compared to algorithms with logarithmic or constant average-case complexities.
  • Worst-Case Performance: In the worst-case scenario, where the target element is at the end of the list or not present, linear search must examine every element, resulting in the worst performance possible for search operations.
  1. Not Suitable for Large or Frequently Accessed Datasets

In applications where datasets are large or frequently accessed, the inefficiencies of linear search become more pronounced.

  • Big Data Applications: For big data applications involving millions or billions of records, linear search is impractical due to its high time complexity. More efficient algorithms are needed to handle such large volumes of data.
  • High-Frequency Queries: In systems where search operations are performed frequently, the cumulative inefficiency of linear search can significantly degrade overall system performance.
  1. Energy Consumption and Resource Usage

In resource-constrained environments, such as embedded systems or mobile devices, the inefficiencies of linear search can lead to higher energy consumption and resource usage.

  • Increased Processing Time: The longer processing time required by linear search translates to higher energy consumption, which can be a critical factor in battery-powered devices.
  • Resource Inefficiency: The need to access each element sequentially can lead to inefficient use of CPU and memory resources, impacting the performance of other concurrent processes.
  1. Limited Optimization Potential

Linear search offers limited potential for optimization compared to more sophisticated algorithms. Its inherent sequential nature restricts opportunities for significant performance improvements.

  • Algorithmic Constraints: The fundamental approach of checking each element one by one limits the scope for optimization. While minor improvements may be possible, they do not change the overall time complexity.
  • Parallelization Challenges: Linear search does not easily lend itself to parallelization. While it can be split across multiple threads, the overhead and complexity involved often outweigh the benefits for most practical purposes.
  1. Suboptimal for Multi-Condition Searches

Linear search is not well-suited for multi-condition searches where multiple criteria must be evaluated to determine a match.

  • Complex Condition Evaluation: Evaluating complex conditions for each element can further slow down the search process. More advanced algorithms can often handle such scenarios more efficiently.
  • Lack of Flexibility: Linear search lacks the flexibility to handle complex queries involving multiple attributes or nested conditions without a significant performance penalty.
  1. Inapplicability to Sorted Data Advantages

When working with arranged information, linear search does not make use of the built-in sequence of the data to enhance search speed.

  • Neglecting Order: Linear search doesn't exploit the sorted nature of datasets, leading to a similar O(n) time complexity as seen with unsorted data. Conversely, algorithms like binary search fully utilize sorted data, providing significantly quicker search times.
  • Overlooked Optimization Potential: The failure to leverage sorted data results in linear search overlooking chances for optimization that could greatly minimize search durations. Comparison with Different Search Algorithms

Although linear search serves as a foundational concept, recognizing its constraints is crucial for gaining a deeper understanding and appreciation of more advanced and efficient algorithms:

Binary Search: In order to implement binary search, the dataset must be arranged in a sorted manner. This algorithm boasts a time complexity of O(logn), which results in notably faster performance when compared to linear search, especially with extensive datasets. Nonetheless, the prerequisite of having data sorted can pose a limitation.

Hashing: Hash-based retrieval techniques, such as the ones employed in hash tables, provide search operations with an average time complexity of O(1). Nonetheless, they introduce added intricacy related to the creation of hash functions and management of collisions.

Two-Way Linear Search Concept

The Two-Point Linear Search technique is an upgraded iteration of the standard linear search algorithm, engineered to enhance search efficiency by inspecting a list from both its start and end points concurrently. In contrast to the conventional linear search method that inspects elements one after the other from the start to the end of the list, the two-point linear search method introduces a more effective strategy by utilizing two pointers: one initiated from the start and the other from the end. This methodology has the potential to notably diminish the quantity of comparisons required to locate the desired element, particularly in cases where the target element is situated close to either extremity of the list.

How does it Works?

The Dual Linear Search method starts by setting up two pointers: one at the beginning and the other at the end of the given list. During each loop, the procedure checks the target value against the elements pointed to by both markers. If a match is detected at either position, the search stops, and the corresponding index is returned. In the absence of a match, the left pointer advances one position to the right, and the right pointer shifts one place to the left. This pattern repeats until the left pointer overtakes the right pointer, signaling that the target element is not within the list if no match was identified until that point.

Initialization:

  • Assign the value 0 to the left pointer, representing the start of the list.
  • Assign the value of the last index of the list (n-1, where n is the list's element count) to the right pointer.

Comparison and Match Check:

  • Compare the element at the lefcpp tutorialer with the target.
  • Compare the element at the righcpp tutorialer with the target.
  • If a match is found at either pointer, return the respective index.

If there is no match, increase the left pointer by 1.

Decrease the right pointer by 1.

Termination:

  • The search process stops when the left pointer surpasses the right pointer.
  • In case the search operation completes without locating a match, -1 is returned to signify that the target element is not present in the list.
  • Implementation in C++

Below is a C++ representation of the Two-Way Linear Search algorithm:

Example

#include <iostream>
#include <vector>

int twoWayLinearSearch(const std::vector<int>& arr, int target) {
    int left = 0;
    int right = arr.size() - 1;

    while (left <= right) {
        if (arr[left] == target) {
            return left;  // Target found on the left side
        }
        if (arr[right] == target) {
            return right;  // Target found on the right side
        }
        ++left;
        --right;
    }
    return -1;  // Target not found
}

int main() {
    std::vector<int> data = {4, 2, 7, 1, 3, 9, 5};
    int target = 7;
    int result = twoWayLinearSearch(data, target);

    if (result != -1) {
        std::cout << "Element found at index " << result << std::endl;
    } else {
        std::cout << "Element not found" << std::endl;
    }
    return 0;
}

Output:

Output

Element found at index 2

Explanation:

In this instance, the method sets up two pointers: 'left', which commences from the start of the array (0), and 'right', which begins from the array's end (arr.size - 1). The method goes into a while loop that persists while 'left' is less than or equal to 'right'. Inside the loop, the method initially verifies if the element at the 'left' position is equivalent to the target. If so, the method returns the 'left' index, signaling that the target was discovered on the left side of the array. Furthermore, the 'right' pointer is decremented, effectively narrowing down the search scope from both ends.

In the primary function, a vector named data is set up with the elements {4, 2, 7, 1, 3, 9, 5}, and the desired value to locate is established as 7. The twoWayLinearSearch method is invoked with data and target as parameters, and the outcome is saved in the variable named result. If the result is anything other than -1, the code displays the position where the desired element was located. If the result is -1, it outputs "Element not found".

When the target 7 is located at index 2 as per the given input, the software displays "Item discovered at index 2." This technique enhances the search operation by inspecting the vector from both ends at the same time, which may decrease the required comparisons in contrast to a standard linear search that initiates from one end.

Advantages of Two-Way Linear Search

The Two-Way Linear Search algorithm represents an improvement upon the standard linear search method, offering notable advantages through the optimization of search procedures. In the following sections, we will explore these benefits extensively, underscoring the reasons behind the Two-Way Linear Search's importance in the arsenal of a programmer.

  1. Decreased Comparison Count

One of the primary advantages of the Two-Way Linear Search is the reduction in the number of comparisons required to find a target element. By leveraging two pointers-one starting at the beginning of the list and the other at the end-the algorithm can potentially locate the target in half the number of comparisons needed by a standard linear search.

  • Best-Case Scenario: In the best-case scenario, the target element is found at either the very beginning or the very end of the list. This results in the target being found in just one comparison, offering a significant improvement over the worst-case scenario of a basic linear search where it might take n comparisons (with n being the number of elements in the list).
  • Average-Case Scenario: Even in the average case, where the target might be somewhere in the middle of the list, the two-way linear search effectively reduces the search space from both ends, making the expected number of comparisons approximately n/2, which is more efficient than the n comparisons in a standard linear search.
  1. Simplicity and Ease of Implementation

Despite its improved efficiency, the Two-Way Linear Search maintains the simplicity that makes the basic linear search so appealing. The algorithm does not require complex data structures or advanced programming techniques, making it easy to implement and understand. This simplicity makes it particularly suitable for:

  • Educational Purposes: Teaching the fundamentals of search algorithms and demonstrating how simple modifications can lead to performance improvements.
  • Quick Prototyping: When quick implementation is more critical than absolute efficiency, the two-way linear search offers a straightforward solution.
  • Code Maintenance: Simple code is easier to maintain and debug, reducing the risk of introducing errors during development or modification.
  1. No Additional Space Requirements

The Two-Way Linear Search algorithm operates with O(1) auxiliary space complexity. This means it only requires a constant amount of extra memory, regardless of the size of the input list. This characteristic is particularly advantageous in environments where memory resources are limited or where minimizing memory usage is crucial.

  • Embedded Systems: In embedded systems and other resource-constrained environments, efficient use of memory is essential. The Two-Way Linear Search is ideal in such contexts because it does not require additional data structures or significant extra memory.
  • Large Data Sets in Memory-Constrained Applications: When working with large datasets that need to be processed in memory-constrained applications, the constant space requirement ensures that the algorithm does not contribute to memory overflow or excessive memory usage.
  1. Versatility

The Two-Way Linear Search is versatile and can be applied to a wide range of scenarios, particularly those involving unsorted lists. Unlike more sophisticated search algorithms such as binary search, which require sorted data, the Two-Way Linear Search can be used directly on any list without prior sorting.

  • Unsorted Data: The algorithm is particularly useful when dealing with unsorted data, where sorting the list might be infeasible or undesirable.
  • Dynamic Data: In situations where data is frequently inserted or deleted, maintaining a sorted list can be cumbersome. The Two-Way Linear Search provides a simple search method that does not rely on sorted data.
  1. Improved Performance in Specific Data Patterns

In many real-world applications, data is not uniformly distributed, and the position of the target element can exhibit specific patterns. The Two-Way Linear Search excels in scenarios where the target element is more likely to be found near the beginning or the end of the list.

  • Partially Sorted Lists: In partially sorted lists or lists where elements are frequently accessed from the ends (e.g., queues, deques), the Two-Way Linear Search can offer significant performance improvements.
  • Common Data Access Patterns: For applications where the most frequently accessed data tends to be near the ends of the list (such as recent transactions or log entries), this algorithm can provide faster access times.
  1. Robustness to List Modifications

The Two-Way Linear Search is robust to modifications in the list, such as insertions or deletions. Unlike binary search, which requires maintaining a sorted order, the two-way approach does not impose such constraints, making it more adaptable to dynamic datasets.

  • Insertion and Deletion Operations: Since the list does not need to remain sorted, elements can be inserted or deleted without the need for re-sorting. This flexibility makes the Two-Way Linear Search suitable for applications with frequent data updates.
  • Dynamic Lists: For applications that deal with dynamic lists, where the size and contents of the list change frequently, the Two-Way Linear Search offers a straightforward and efficient search method.
  1. Performance Consistency

The performance of the Two-Way Linear Search is consistently better or at least equal to the standard linear search across various scenarios. This consistency is valuable when predictability and reliability are required.

  • Predictable Performance: In applications where performance predictability is important, knowing that the search will complete within a reasonable time frame (even in the worst-case scenario) is beneficial.
  • Balanced Performance: The algorithm provides a good balance between simplicity and efficiency, making it suitable for a wide range of applications without the need for complex optimizations.
  1. Applicability to Various Data Types

The Two-Way Linear Search is not limited to numeric data; it can be applied to lists containing various data types, including strings, objects, and more complex structures. This flexibility makes it a versatile tool in diverse programming contexts.

  • String Searches: In lists of strings, the algorithm can be used to find a specific string by comparing each element from both ends.
  • Object Searches: In lists of objects, where each object has a unique identifier or key, the Two-Way Linear Search can efficiently locate the target object.
  1. Combining with Other Algorithms

The Two-Way Linear Search can be combined with other algorithms to enhance overall system performance. For example, it can be used as a preliminary search method before applying more complex algorithms.

  • Hybrid Search Methods: In hybrid search methods, the Two-Way Linear Search can serve as a fast initial pass to quickly rule out targets near the ends, followed by a more detailed search in the remaining portion of the list.
  • Preprocessing Step: In some applications, the Two-Way Linear Search can be used as a preprocessing step to narrow down the search space for more computationally intensive algorithms.
  1. Educational Tool

Finally, the Bidirectional Linear Search acts as a valuable educational resource. It familiarizes students and novice developers with the idea of enhancing fundamental algorithms by making straightforward adjustments, offering a gateway to more sophisticated algorithmic reasoning.

  • Algorithmic Thought Process: Comprehending the Bidirectional Linear Search aids students in recognizing the significance of streamlining and effectiveness in algorithm creation.
  • Real-World Implementations: Mastering the implementation and utilization of the Bidirectional Linear Search equips students with hands-on expertise that can be directly employed in tackling real-world programming dilemmas.
  • Use Cases

The Two-Way Linear Search algorithm is useful in various scenarios:

  • Small to Medium-Sized Lists: For small and medium-sized lists, the reduction in the number of comparisons can lead to noticeable performance improvements without adding significant complexity.
  • Unsorted Data: When dealing with unsorted lists, where sorting the data might be infeasible or unnecessary, the two-way linear search offers a simple yet efficient search method.
  • Specific Data Patterns: In cases where the target element is more likely to be near the ends of the list (e.g., in partially sorted lists or when elements are added to the ends), this algorithm can provide quicker results.
  • Performance Analysis

Best Case

In an ideal situation, the desired element is positioned either at the start or the conclusion of the list. This results in the algorithm successfully locating the target with only a single comparison.

Time Complexity: O(1)

Average Case

In a typical situation, the desired element is usually positioned towards the center of the list. The bidirectional linear search method generally locates the target by conducting only half the number of comparisons as the traditional linear search technique:

Time Complexity: O(n/2)=O(n)

Worst Case

In the event of the worst-case scenario, the desired element may either be absent from the list or positioned at the list's midpoint. The algorithm is required to navigate from both ends until the pointers intersect:

Time Complexity: O(n)

Practical Considerations

Handling Duplicates

If duplicates of the target element are present in the list, the bidirectional linear search will locate the first instance it comes across, irrespective of whether it's from the beginning or the end of the list. To ensure consistent handling of duplicates according to the particular criteria, supplementary logic may be necessary.

  • When encountering an empty list, the algorithm needs to promptly return -1 to manage this scenario effectively.
  • In the case of a list containing only one element, the algorithm must verify whether this sole element corresponds to the target value.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience