Java:向后递归线性搜索

时间:2015-10-26 22:52:19

标签: java search recursion indexing linear

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

<module id="javax.persistence" javadoc="http://java.sun.com/javaee/5/docs/api"/>

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

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);
}

或者那种性质的东西,但是想知道是否有一种更简单的方法,我只能使用一个函数但保持递归?

1 个答案:

答案 0 :(得分:2)

不容易但只有一个功能:

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);
}
}