向后递归线性搜索

Backward Recursive Linear Search

我正在尝试编写一个函数,通过修改线性搜索函数来查找向量中目标的最后一次出现。

private int linearSearchRecursive(int[] input, int key,int index) {
    if (index == 0) {
        return -1;
    }
    if (input[index] == key) {
        return index;
    }
    else 
    return linearSearchRecursive(input,key,--index);
}

我想到了一种使用辅助函数使其工作的方法...

public static int findLastOccurance(int[] items, int key){
    return linearSearchRecursive(items, key, items.length - 1);
}

或者类似的东西,但想知道是否有更简单的方法可以只使用一个函数但保持递归性?

不简单但只有一个功能:

public class Test {

public static int findLastOccuranceRecursive(int[] input, int key, int... optionalIndex) {
    if (optionalIndex.length == 0) {
        optionalIndex = new int[] { input.length - 1 };
    } else if (optionalIndex.length != 1) {
        throw new IllegalArgumentException("size of optionalIndex must be 0 or 1");
    }

    if (optionalIndex[0] == 0) {
        return -1;
    }
    if (input[optionalIndex[0]] == key) {
        return optionalIndex[0];
    } else {
        optionalIndex[0]--;
        return findLastOccuranceRecursive(input, key, optionalIndex);
    }
}

public static int findLastOccuranceIterative(int[] items, int key) {
    for (int i = items.length - 1; i >= 0; i--) {
        if (items[i] == key) {
            return i;
        }
    }
    return -1;
}

public static void main(String[] args) {
    int[] input = { 1, 1, 1, 2, 1, 2, 1, 1 };
    int testRecursive = findLastOccuranceRecursive(input, 2);
    int testIterative = findLastOccuranceIterative(input, 2);
    System.out.println("testRecursive: " + testRecursive + " testIterative: " + testIterative);
}
}