通过二进制搜索帮助递归(Java)
Recursive via Binary Search Help(Java)
我们被告知使用 class 递归进行二分查找。然而,我被困住了,因为根据我的教授(当我寻求帮助时没有详细说明)递归无法正常工作并且一直在与同学一起工作。我们得出需要 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
你调用的参数有误,请尝试调用
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(10000));
}
我们被告知使用 class 递归进行二分查找。然而,我被困住了,因为根据我的教授(当我寻求帮助时没有详细说明)递归无法正常工作并且一直在与同学一起工作。我们得出需要 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
你调用的参数有误,请尝试调用
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(10000));
}