Write a recursive, boolean -valued method named search that accepts an integer array , the number of elements in the array, and an integer (in that order), and returns whether the integer is present as an element in the array.

1
Write a recursive, boolean -valued  method named search that accepts an integer  array , the number of elements in the array, and an integer  (in that order), and returns whether the integer is present as an element in the array.

LANGUAGE: JAVA

CHALLENGE:

Write a recursive, boolean -valued method named search that accepts an integer array , the number of elements in the array, and an integer (in that order), and returns whether the integer is present as an element in the array. Searching for a particular value in an array can be performed in the following recursive manner:
• If the array has no elements , the value is not there.
• Compare the first element of the array to the value , if they’re equal , the value is there; other search for the value in the rest of the array .

SOLUTION:

public static boolean search(int[] elements, int size, int value)
{
    boolean found=false;
    if(size>0)
    {
        if(elements[size-1]==value)
            return found=true;
    }
    else
        return search(elements, size-1, value);
    
    return found;
}

One comment

  • superwilk says:

    public static boolean search(int arr[],int n, int m){
    if(n==0){
    return false;
    }
    if(arr[n-1]==m){
    return true;
    }
    n=n-1;
    return search(arr,n,m);
    }

Add comment