Given an array arr[] of n elements, write a function to recursively search a given element x in arr[].
Illustration:
Input : arr[] = {25, 60, 18, 3, 10}
Output : Element to be searched : 3
Input : arr[] = {10,20,30,24,15,40}
Output : -1
For x = 35
Element x is not present in arr[]
Procedure:
The idea is to search the element from both the sides of array recursively. If the element that needs to searched matches with the leftmost element of the left boundary, or it matches with the rightmost element of the right boundary, directly return the position of the element, else recur for the remaining array to search for the element with the value same as x.
Example
Java
public class GFG {
static int recursiveSearch( int arr[], int l, int r,
int x)
{
if (r < l)
return - 1 ;
if (arr[l] == x)
return l;
if (arr[r] == x)
return r;
return recursiveSearch(arr, l + 1 , r - 1 , x);
}
public static void main(String[] args)
{
int x = 3 ;
int arr[] = new int [] { 25 , 60 , 18 , 3 , 10 };
int index
= recursiveSearch(arr, 0 , arr.length - 1 , x);
if (index != - 1 )
System.out.println( "Element " + x
+ " is present at index "
+ index);
else
System.out.println( "Element " + x
+ " is not present" );
}
}
|
OutputElement 3 is present at index 3
Time complexity: O(N2) where N is size of input array
Auxiliary Space : O(N)