使用递归查找数组中的最小数字

时间:2016-04-01 17:18:06

标签: java arrays recursion

当我剖析我的代码的逻辑时,它对我来说是有意义的,看起来它应该工作。我需要使用递归查找并返回数组中的最小数字。这是我的代码

public static int findMin(int[] numbers, int start, int last)
{
    int min = numbers[start]; // sets first value in array to minimum

    if(numbers[start]<numbers[last]&& numbers[start]<min)
    {   // if 1st value < last value in array and 1st value smaller than min, set min to first value
        min = numbers[start];

    }
    else if(numbers[start]>numbers[last]&& numbers[last] < min)
    {   // if 1st value > last value and last value < min, set min to last value
        min = numbers[last];
    }
    else
    {   // if 1st and last value are equal returns 1st value
        return numbers[start];
    }
        // recursively calls... or not
    findMin(numbers, start+1, last-1);
    return min;
}

使用的输入是33 -55,-44,12312,2778,-3,-2,53211,-1,44,0

输出获取:

最小数字为0 线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:-1     在Assignment9.countEven(Assignment9.java:72)     在Assignment9.countEven(Assignment9.java:87)     在Assignment9.main(Assignment9.java:34)

预计:-55

我假设我的递归调用放错了。请帮忙,谢谢。

3 个答案:

答案 0 :(得分:2)

这应该可以解决问题

class ChoicePersonView(FormView):
    template_name = 'guess_houses.html'
    form_class = PersonListForm

    def get(self, request, *args, **kwargs):
        form = self.form_class(initial=self.initial)
        return render(request, self.template_name, {'form': form})

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            persons_id = form.cleaned_data['persons']
            houses = [] # list of houses i want to display
            t1 = time()
            comb = [] # I need all houses, where lived any of these persons
            for r in range(1, len(persons_id )+1):
                comb += [i for i in combinations(persons_id ,r)]
            for id_person_dict in House.objects.all().values('id', 'persons', 'name'):
                for c in comb:
                    if set(c).issubset(set(id_person_dict['persons'])): 
                        if id_person_dict not in houses:
                            houses.append(id_person_dict)
        return render(request, self.template_name, {'form': form, 'houses': houses, 't': time() - t1})

如果由于某种原因您无法使用Math.min,您可以随时使用:

public static int findMin(int[] numbers, int start, int last)
{
    if(start == last) return numbers[0];
    return Math.min(numbers[start],findMin(numbers, start+1, last));
}

主要问题或解决方案是:

- &GT;你没有正确检查停止案例;

- &GT;您没有使用每次递归调用中计算的最小值;

- &GT;而且你没有检查你超过数组限制的情况。

答案 1 :(得分:0)

乍一看,看起来你没有保存递归调用的结果,你只是把它称为无效方法。

而不是

findMin(numbers, start+1, last-1);
return min;

尝试:

min = findMin(numbers, start+1, last-1);
return min;

答案 2 :(得分:0)

为什么不简单试试这个:

    public static int  findMin(int[] numbers, int start, int last) {
        if(start == last){
            return numbers[start];
        }

        if(numbers[start] <= numbers[last]) {
            last -= 1;
        } else {
            start += 1;
        }

        return findMin(numbers, start, last);
    }

或者你可以按照Qriss的建议使用Divide and Conquer策略:

    public static int findMin(int[] numbers){
        return findMinHelper(numbers, 0, numbers.length);
    }

    public static int findMinHelper(int[] numbers, int left, int right){
        int min1 = 0, min2 = 0;

        if (left == right - 1){
            return numbers[left];
        } else {
              min1 = findMinHelper(numbers, left, (right + left) / 2);
              min2 = findMinHelper(numbers, (right + left) / 2, right);
        }

        return (min1 < min2) ?  min1 : min2;
    }