繁体   English   中英

递归方法,比较数组中的所有元素并返回索引

[英]recursive method that compares all elements in array and returns index

我正在尝试创建递归方法,返回等于X的元素的索引。我们有一些数组和数字X.我需要将X与数组中的所有数字进行比较并返回等于的数字的索引X。

这是我的试用版:

public static void main(String[] args) throws Exception {

    final List<Integer> numbers = new ArrayList<Integer>() {
            {
                add(3);
                add(4);
                add(6);
                add(1);
                add(9);
            }
        };

        final int x = 3;
    }

所以findSmallest返回最小的元素。 如果我们在找到您要找的元素时停止怎么办?

像这样:

private static final int findSame(Iterator<Integer> iterator, Integer x, int idx) {
    if (!iterator.hasNext()) {
        // Don't have a next! return -1
        return -1;
    }

    if (iterator.next().equals(x)) {
        // Found it!
        // Let's give back the current index.
        return idx;
    } else {
        // Not here, lets check the rest.
        return findSame(iterator, x, idx+1);
    }
}

所以你只是第一次用idx 0来调用它。

由于您没有使用有效的语法,因此您将遇到其他问题。

主要代码应该是:

final List<Integer> numbers = Arrays.asList(3, 4, 6, 1, 9);
final Integer x = Integer.valueOf(3);
System.out.println(findSame(numbers.iterator(), x, 0));

如果您正在尝试这样做,那么它的代码非常简单。 相信我。 这是Java代码的细分:

private static int FindIt(int[] arr, boolean it, int index, int want)
{
    //want is the wanted number
    //The integer index should be set at 0 in the beginning. It is the index of the array
    //The boolean it represents if we find it. 
    //The base case
    if (it){
    return index;
    }
    else if (index == arr.length){
    //The usual not found factor
    return -1;
    }
    else{
    //Advance it if you don't find it
        if (arr[index] == want){
                return index;
        }
        else{
        return FindIt(arr, it, index+1);
        }
    }
}   

这实际上就是你所要做的。 我希望它有所帮助!

这是代码中的一些编辑。 它可以用更简单的方式编写,而无需使用ArrayList。


import java.util.ArrayList; import java.util.List;
class RecursionForSearching {

static List<Integer> numbers;

public static void main(String[] args) throws Exception {

    numbers = new ArrayList<Integer>() {
        {
            add(3);
            add(4);
            add(6);
            add(1);
            add(9);
        }

    };
    int x = 1;
    int result = searchNum(x, 0);
    if (result != -1) {
        System.out.println("There is x in the array, and the index is: " + result);
        System.out.println("There is x in the array, and the Position is: " + (result + 1));
    } else
        System.out.println("X is not found in List");
}

private static int searchNum(int x, Integer index) {

    if (index == numbers.size())
        return -1;
    if (!(numbers.get(index) == x)) {
        return searchNum(x, index + 1);
    }

    return index;
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM