найти первый индекс числа в массиве через рекурсию - PullRequest
0 голосов
/ 20 января 2020

Так что в этой задаче я пытаюсь найти индекс заданного числа в массиве с помощью рекурсии, он дает неправильный вывод. Любая помощь будет оценена. Вот мой код:

public class first_index {
// i refers to index, x is element
    public static int firstIndex(int input[], int x,int i){

        if(i >= input.length - 1){
            if(input[i]==x)
                return i;
            else
                return -1;
        }
        int b;
        b=firstIndex(input,x,i+1);
        if(b!=-1){
            if(input[i]==x)
                return i+1;
            else
                return i-1;
        }
        else{
            if(input[i]==x)
                return i;
            else
                return -1;
        }
        }

    public static void main(String[] args) {
        int input[] = {1,2,3,5,9,0};
        System.out.println(firstIndex(input,9,0));

    }
}

Ответы [ 2 ]

1 голос
/ 20 января 2020

Если текущий индекс содержит искомое число, вы должны вернуть этот индекс.

Только если этого не произойдет, вы должны сделать рекурсивный вызов для поиска номера в оставшейся части массив.

public static int firstIndex(int input[], int x,int i) {
    if (i > input.length - 1) { // i is beyond the indices of the array, 
                                // so the number is not found
        return -1;
    }

    if(input[i]==x) { // current index is the first index that contains x
        return i;
    } else { // make a recursive call to find the first index of x in the rest of the array
        return firstIndex(input,x,i+1);
    }
}

, который также может быть записан как:

public static int firstIndex(int input[], int x,int i) {
    if(i > input.length - 1) {
        return -1;
    }

    return (input[i] == x) ? i : firstIndex(input, x, i+1);
}
0 голосов
/ 20 января 2020

Как насчет:

public static int firstIndex(int input[], int x,int i){
    if(i >= input.length) {
        return -1;
    } else if(input[i]==x)
        return i;
    } else {
        return firstIndex(input,x,i+1);
    }
}
...