Java linear search program using recursion

Example

package com.w3spoint;
 
public class Test {
     public static int recSearch(int data[], int l, int r, int key) {
        if (r < l)
           return -1;
        if (data[l] == key)
           return l;
        return recSearch(data, l+1, r, key);
    }
 
    public static void main(String args[]){
	int[] data= {50,27,30,50,70,9,19};    
        int key = 9;    
 
        int index = recSearch(data, 0, data.length-1, key);
        if (index != -1)
           System.out.println("Element " + key + " is present at index " + index);
        else
            System.out.println("Element " + key + " is not present");
    }
}

Output

9 is found at index: 5
Please follow and like us:
Content Protection by DMCA.com