【发布时间】:2016-03-16 21:42:14
【问题描述】:
我正在尝试递归地在数组中找到两个差异最小的元素(假设数组已经按升序排序)。
我一直试图让我的代码只返回最小的和,但递归似乎无法正常工作。
public class SmallestDiff {
public static void main (String [] args){
int [] x = {1,3,6,9,126};
System.out.println(smallestDiff(x,4));
}
public static int smallestDiff (int [] array, int index){
int result;
if (index>0){
int diff = Math.abs((array[index]-array[index-1]));
result = Math.min (diff, smallestDiff(array,index-1));
}
else {
return array[0];
}
return result;
}
}
【问题讨论】:
-
我认为这应该是对递归技术的培训。在实践中,您的任务应该通过迭代来解决。
标签: java arrays algorithm recursion difference