Open In App

Two Way Linear Search Algorithm

Last Updated : 15 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Two-Way Linear Search Algorithm is based on the principle of Linear Search, but the search is conducted from both ends towards the center of the array. In this article, we will learn about the basics of Two Way Linear Search Algorithm, its advantages, implementation etc.

What is Two-Way Linear Search?

Two Way Linear Search is a searching technique where we start our search from both the ends of the array simultaneously and move towards the center until we find the target element.

We maintain two pointers, one pointing at the start and other pointing at the end and compare elements at start and end with the target element. If any of them is equal to target, then we know that we have found the target element. Otherwise, we move start to the next index and move end to the previous index and again compare the corresponding elements. Two Way Linear Search stops either when we find the target element or when start and end cross each other (start > end).

Algorithm for Two-Way Linear Search:

Below is the step-by-step algorithm for Two-Way Linear Search:

  • Initialize the search indices start=0 and end=N-1 (where N is the size of the array).
  • While the elements at indexes start and end are not equal to the search element, increment start by 1 and decrement end by 1.
  • Continue looping until start <= end; the loop terminates once it reaches the middle of the array.
  • If the element is found, return its index; otherwise, return -1.

Implementation of Two-Way Linear Search Algorithm:

Below is the implementation of Two-Way Linear Search Algorithm:

C++
#include <iostream>
using namespace std;
// Function to perform Two Way Linear Search
int search(int arr[], int target, int size)
{
    // Initialize the starting and ending pointers
    int start = 0, end = size - 1;

    // Iterate till start and end cross each other
    while (start <= end) {
        // If the start element is equal to target, return
        // start as the index of target element
        if (arr[start] == target) {
            return start;
        }
        // If the ending element is equal to target, return
        // end as the index of target element
        if (arr[end] == target) {
            return end;
        }
        // If target is not equal to starting or ending
        // element, increment start by 1 and decrement end
        // by 1
        start++;
        end--;
    }
    // Return -1 if the target element is not found
    return -1;
}
// Driver code
int main()
{
    // Sample Input
    int arr[] = { 3, 9, 12, 16, 20 };
    int target = 12;
    int size = sizeof(arr) / sizeof(arr[0]);
    int pos = search(arr, target, size);
    if (pos == -1) {
        cout << "Element is not present in array" << endl;
    }
    else {
        cout << "Element is present at index " << pos
             << endl;
    }
    return 0;
}
Java
public class Main {
    // Function to perform Two Way Linear Search
    public static int search(int[] arr, int target,
                             int size)
    {
        // Initialize the starting and ending pointers
        int start = 0, end = size - 1;

        // Iterate till start and end cross each other
        while (start <= end) {
            // If the start element is equal to target,
            // return start as the index of target element
            if (arr[start] == target) {
                return start;
            }
            // If the ending element is equal to target,
            // return end as the index of target element
            if (arr[end] == target) {
                return end;
            }
            // If target is not equal to starting or ending
            // element, increment start by 1 and decrement
            // end by 1
            start++;
            end--;
        }
        // Return -1 if the target element is not found
        return -1;
    }

    // Driver code
    public static void main(String[] args)
    {
        // Sample Input
        int[] arr = { 3, 9, 12, 16, 20 };
        int target = 12;
        int size = arr.length;
        int pos = search(arr, target, size);
        if (pos == -1) {
            System.out.println(
                "Element is not present in array");
        }
        else {
            System.out.println(
                "Element is present at index " + pos);
        }
    }
}

// This code is contributed by shivamgupta310570
Python
# Function to perform Two Way Linear Search
def search(arr, target):
    # Initialize the starting and ending pointers
    start = 0
    end = len(arr) - 1

    # Iterate till start and end cross each other
    while start <= end:
        # If the start element is equal to target, return
        # start as the index of target element
        if arr[start] == target:
            return start
        # If the ending element is equal to target, return
        # end as the index of target element
        if arr[end] == target:
            return end
        # If target is not equal to starting or ending
        # element, increment start by 1 and decrement end
        # by 1
        start += 1
        end -= 1
    # Return -1 if the target element is not found
    return -1


# Driver code
if __name__ == "__main__":
    # Sample Input
    arr = [3, 9, 12, 16, 20]
    target = 12
    pos = search(arr, target)
    if pos == -1:
        print("Element is not present in array")
    else:
        print(f"Element is present at index {pos}")
JavaScript
// Function to perform Two Way Linear Search
function search(arr, target, size) {
    // Initialize the starting and ending pointers
    let start = 0, end = size - 1;

    // Iterate till start and end cross each other
    while (start <= end) {
        // If the start element is equal to target,
        // return start as the index of target element
        if (arr[start] === target) {
            return start;
        }
        // If the ending element is equal to target,
        // return end as the index of target element
        if (arr[end] === target) {
            return end;
        }
        // If target is not equal to starting or ending
        // element, increment start by 1 and decrement
        // end by 1
        start++;
        end--;
    }
    // Return -1 if the target element is not found
    return -1;
}

// Driver code
function main() {
    // Sample Input
    const arr = [3, 9, 12, 16, 20];
    const target = 12;
    const size = arr.length;
    const pos = search(arr, target, size);
    if (pos === -1) {
        console.log("Element is not present in array");
    } else {
        console.log("Element is present at index " + pos);
    }
}

main();

Output
Element is present at index 2

Time Complexity : O(N), where N is the size of input array arr[]
Auxiliary Space : O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads