javaarraysrecursiontail-recursionarray-algorithms

Recursion method is invoked even after loop condition is met


public int removeMin(Integer[] arr, int count) {
    Integer[] tempArr = new Integer[arr.length -1];
    
    int index = 0;
    for (int i = 1; i<arr.length; i++) {
        tempArr[index] = arr[i] - arr[0];
        index++;
    }
    count = count+1;
    if (tempArr.length == 0){
        return count;
    }else{
        removeMin(tempArr, count);
    }
    return count;
}

I want the function to return count as 4 when tempArr.length == 0.

Input parameters:

Integer[] arr = {2,5,8,11};
int count = 0;

I am expecting it to return 4 but it's returning 1.


Solution

  • You need to change your conditional and your returns as follows.

    if (tempArr.length != 0){
       return removeMin(tempArr, count);
    }
    return count;
    

    Here's the complete code.

    public static  int removeMin(int[] arr, int count) {
         int[] tempArr = new int[arr.length -1];
         
         int index = 0;
         for (int i = 1; i<arr.length; i++) {
             tempArr[index] = arr[i] - arr[0];
             index++;
         }
         count = count+1;
         if (tempArr.length != 0){
             return removeMin(tempArr, count);
         }
         return count;
     }
    

    But isn't count always going to be equal to the array size. So what are you trying to do?