Front and Back Search in unsorted array - GeeksforGeeks

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:  
Initialize indexes front and back pointing to first and last element respectively of the array.If front is greater than rear, return false.Check the element x at front and rear index.If element x is found return true.Else increment front and decrement rear and go to step 2.
Initialize indexes front and back pointing to first and last element respectively of the array.
If front is greater than rear, return false.
Check the element x at front and rear index.
If element x is found return true.
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++
Java
Python3
C#
PHP
Javascript
// 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 program to implement front and back// searchclass 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.
# 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 codearr = [10, 20, 80, 30, 60,       50, 110, 100, 130, 170]x = 130n = len(arr) if (search(arr, n, x)):    print("Yes")else:    print("No")     # This code is contributed by Anant Agarwal.
// C# program to implement front and back// searchusing 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 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?>
<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>
Yes
 
jit_t
avijitmondal1998
Arrays
Searching
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Maximum and minimum of an array using minimum number of comparisons
Multidimensional Arrays in Java
Linked List vs Array
Queue | Set 1 (Introduction and Array Implementation)
Maximum and minimum of an array using minimum number of comparisons
Program to find largest element in an array
Find the Missing Number
Program to remove vowels from a String
Find the index of an array element in Java