DEV Community

Yesh Rajawat
Yesh Rajawat

Posted on

Check whether a number is in an array or not using recursion

public class Check_Number {


    public static boolean checkNumber(int i , int find, int []arr) {

        if(i==arr.length) {
            return false;
        }
        else {
            if( arr[i] == find ) {

                return true;

            }
            else {

                return checkNumber(i+1,find,arr); 

            }
        }

    }

    public static void main(String ... args) {

        int [] arr = {1,2,3,4,5,6,7};
        System.out.println(checkNumber(0,10,arr));

    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
cess11 profile image
PNS11

Does Java have tail call optimisation now? If not, what are the advantages to this approach compared to Arrays.binarySearch(arr, find), Arrays.asList(arr).contains(find) or the various stream-related techniques?

Collapse
 
yeshrajawat profile image
Yesh Rajawat

No, Java does not support tail call optimization, and we cannot use Arrays.binarySearch(arr, find) as first we will have to sort the array first as binary search works only on sorted arrays. As far as Arrays.asList(arr) concern we first have to convert our array into Arraylist which would definately take time so solving it like this would be better than Arrays.asList(arr).contains(find). But if we have array list instead of fixed size array then we can go for that option.