我们被告知使用递归类进行二分搜索。但是,由于我的教授(我寻求帮助时没有详细说明)并且一直在与一位同学一起工作,因此我被困住了,因为递归无法正常工作。我们得出需要 int count 的结论,但我不确定在哪里或如何实现它。Java 不是我最擅长的语言,因此指南或提示会非常有帮助。
public class Recursive {
public int BinarySearch(int x[], int target, int low, int high)
{
if (low >= high) return -1;
int mid = (low + high)/2;
if (x[mid] > target)
return BinarySearch(x, target, low, mid-1);
else if (x[mid] < target)
return BinarySearch(x, target, mid+1, high); ;
return mid;
}
public int firstNnumber(int n)
{
if (n < 1) return 0;
return firstNnumber(n-1) + n;
}
public int firstNnumber2(int n)
{
if (n==1) return 1;
if (n==2) return 3;
boolean even = (n%2 == 0);
n /= 2;
if (even)
{
return 2*firstNnumber2(n) + n*n;
}
else
return 2*firstNnumber2(n) + (n + 1)*(1+n);
}
public int gaussian(int n)
{
return n*(n+1)/2;
}
static public void main(String [] args)
{
Recursive r = new Recursive();
System.out.println("By Gussain, Sum of first 100000 integers=" + r.gaussian(10000));
System.out.println("By recurssion 2, Sum of first 100000 integers=" + r.firstNnumber2(6));
}
}
这是打印的,我不明白我的代码有什么问题。
通过 Gussain,前 100000 个整数的总和 = 50005000 通过递归 2,前 100000 个整数的总和 = 21
慕桂英546537
相关分类