Skip to content
Related Articles

Related Articles

Improve Article
Front and Back Search in unsorted array
  • Difficulty Level : Easy
  • Last Updated : 06 Apr, 2021

Given an unsorted array of integers and an element x, find if x is present in array using Front and Back search.
Examples : 
 

Input : arr[] = {10, 20, 80, 30, 60, 50, 
                     110, 100, 130, 170}
          x = 110;
Output : Yes

Input : arr[] = {10, 20, 80, 30, 60, 50, 
                     110, 100, 130, 170}
           x = 175;
Output : No

 

A simple solution is to perform linear search. The linear search algorithm always results in worst case complexity of O(n) when element to be searched is last element in the array. Front and Back search algorithm for finding element with value x works the following way: 
 

  1. Initialize indexes front and back pointing to first and last element respectively of the array.
  2. If front is greater than rear, return false.
  3. Check the element x at front and rear index.
  4. If element x is found return true.
  5. Else increment front and decrement rear and go to step 2.

Key Points: 
 

  • The worst case complexity is O(n/2) (equivalent to O(n)) when element is in the middle or not present in the array.
  • The best case complexity is O(1) when element is first or last element in the array.

 



C++




// CPP program to implement front and back
// search
#include<iostream>
using namespace std;
 
bool search(int arr[], int n, int x)
{
    // Start searching from both ends
    int front = 0, back = n - 1;
 
    // Keep searching while two indexes
    // do not cross.
    while (front <= back)
    {
        if (arr[front] == x || arr[back] == x)
          return true;
        front++;
        back--;
    }
    return false;
}
 
int main()
{
   int arr[] = {10, 20, 80, 30, 60, 50,
                     110, 100, 130, 170};
   int x = 130;
   int n = sizeof(arr)/sizeof(arr[0]);
   if (search(arr, n, x))
      cout << "Yes";
   else
      cout << "No";
   return 0;
}

Java




// Java program to implement front and back
// search
class GFG {
     
    static boolean search(int arr[], int n, int x)
    {
         
        // Start searching from both ends
        int front = 0, back = n - 1;
     
        // Keep searching while two indexes
        // do not cross.
        while (front <= back)
        {
            if (arr[front] == x || arr[back] == x)
                return true;
            front++;
            back--;
        }
         
        return false;
    }
     
    // driver code
    public static void main (String[] args)
    {
        int arr[] = {10, 20, 80, 30, 60, 50,
                        110, 100, 130, 170};
        int x = 130;
        int n = arr.length;
         
        if (search(arr, n, x))
            System.out.print("Yes");
        else
            System.out.print("No");
    }
}
 
// This code is contributed by Anant Agarwal.

Python3




# Python program to implement
# front and back search
 
def search(arr, n, x):
 
    # Start searching from both ends
    front = 0; back = n - 1
     
    # Keep searching while two
    # indexes do not cross.
    while (front <= back):
     
        if (arr[front] == x or arr[back] == x):
            return True
        front += 1
        back -= 1
     
    return False
 
# Driver code
arr = [10, 20, 80, 30, 60,
       50, 110, 100, 130, 170]
x = 130
n = len(arr)
 
if (search(arr, n, x)):
    print("Yes")
else:
    print("No")
     
# This code is contributed by Anant Agarwal.

C#




// C# program to implement front and back
// search
using System;
 
public class GFG {
 
    static bool search(int []arr, int n, int x)
    {
         
        // Start searching from both ends
        int front = 0, back = n - 1;
     
        // Keep searching while two indexes
        // do not cross.
        while (front <= back)
        {
            if (arr[front] == x || arr[back] == x)
                return true;
            front++;
            back--;
        }
         
        return false;
    }
 
    static public void Main ()
    {
        int []arr = {10, 20, 80, 30, 60, 50,
                    110, 100, 130, 170};
        int x = 130;
        int n = arr.Length;
         
        if (search(arr, n, x))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
 
// This code is contributed by vt_m.

PHP




<?php
// PHP program to implement front and back
// search
 
function search($arr, $n, $x)
{
     
    // Start searching from both ends
    $front = 0;
    $back = $n - 1;
 
    // Keep searching while two
    // indexes do not cross.
    while ($front <= $back)
    {
        if ($arr[$front] == $x ||
            $arr[$back] == $x)
        return true;
        $front++;
        $back--;
    }
    return false;
}
 
    // Driver Code
    $arr = array(10, 20, 80, 30, 60, 50,
                     110, 100, 130, 170);
    $x = 130;
    $n = sizeof($arr);
    if (search($arr, $n, $x))
        echo "Yes";
    else
        echo "No";
 
// This code is contributed by aj_36
?>

Javascript




<script>
 
// JavaScript program to implement front and back
 
    function search(arr, n, x)
    {
           
        // Start searching from both ends
        let front = 0, back = n - 1;
       
        // Keep searching while two indexes
        // do not cross.
        while (front <= back)
        {
            if (arr[front] == x || arr[back] == x)
                return true;
            front++;
            back--;
        }
           
        return false;
    }
 
// Driver Code
 
        let arr = [10, 20, 80, 30, 60, 50,
                        110, 100, 130, 170];
        let x = 130;
        let n = arr.length;
           
        if (search(arr, n, x))
            document.write("Yes");
        else
            document.write("No");
 
// This code is contributed by avijitmondal1998.
</script>
Output: 
Yes

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live 




My Personal Notes arrow_drop_up
Recommended Articles
Page :