Return state does not work in Java

I tried a little code to learn about recursion in java. Wrote the method below to implement linear search using recursion. But when I call this method with an array and a variable to search as input, and when the method reaches the return statement, it does not exit the method. Instead, after executing the statements in the if loop, it enters the else loop again.

I have 2 questions.

1) Why does it not exit the method when it reaches the “return”?

2) Why does he introduce an else loop after executing the if loop?

What am I doing wrong here? Can someone please take a look and help me.

linearRecursiveSearch(Constants.INPUT_INT_ARRAY, Constants.INPUT_INT_ARRAY[0], Constants.NUMBER_TO_SEARCH); 



int count = 0;
public <T> void linearRecursiveSearch(T[] array,T tmp, T value) {
    count++;
    if (tmp == value) {
        System.out.println("The value has been found");
        return;
    } else {
        for (int i = count; i < array.length; i++) {
            T tmp1 = array[i];
            linearRecursiveSearch(array,tmp1, value);
        }
    }
}
+4
source share
2

1) ""?

, return.

2) else if?

, return, else. , , , return.


, , .

, , , . , . , . , , , .

. , , , . , , , , return ( ), , . , (, ) .


, , for :

public <T> int linearRecursiveSearch(T[] array, T targetValue) {
    return linearRecursiveSearch( array, targetValue, 0 );
}

private <T> int linearRecursiveSearch(T[] array, T targetValue, int i) {
    if ( i >= array.length ) {
        return -1;
    } else if (array[i] == targetValue) {  
        // == or .equals, or Comparator?  task for the reader
        return i;
    } else {
        return linearRecursiveSearch(array, targetValue,i+1);    
    }
}
+6

,

import groovy.util.logging.Slf4j
import org.junit.Test

@Slf4j
class MyTest {
@Test
public void myTest(){
    int count = 0;
    Integer[] input= [1,2,3,4,5,6,7]
    linearRecursiveSearch(input,5,0)
}

public <T> void linearRecursiveSearch(T[] array, T value,int count) {
    count++;
    if (array[count] == value) {
        System.out.println("The value has been found");
        return;
    } else {

            linearRecursiveSearch(array, value,count);

    }
}

}

+1

Source: https://habr.com/ru/post/1611793/


All Articles