我正在研究递归问题 我打算打电话给它,但它显示如下
import java.util.Arrays;
public class BinarySearch {
public static int binarySearch(int [] list, int key){
int low = 0;
int high = list.length -1;
return binarySearch(list, key, low ,high);
}
public static int binarySearch(int [] list, int key, int low, int high){
if(low > high){
return (-low -1);}
int mid = (low + high) / 2;
if(key < list[mid])
return binarySearch(list, key, low, mid - 1);
else if(key == list[mid])
return mid;
else
return binarySearch(list, key, mid + 1, high);
}
public static void main (String [] args){
int [] list = {'1', '2','4','5'};
binarySearch(list, 4);
System.out.println(Arrays.toString(list));
}
}
输出:[49,50,52,53]
我该怎么做才能使其正确?
答案 0 :(得分:4)
您正在以整数数组存储字符: -
int [] list = {'1', '2','4','5'};
因此,您获得的值分别是1, 2, 4, 5
的ASCII代码。因此,您的binarySearch
方法无法找到值4
。因为,它并不完全存在。删除值周围的单引号。
其次,您不打印return value
binarySearch
方法: -
binarySearch(list, 4);
应该是: -
System.out.println(binarySearch(list, 4));
答案 1 :(得分:1)
您在列表中添加了字符值。
切换这样的单引号,它应该没问题
{1,2,4,5};
因此,在您给定的情况下,您将存储字符“1”,“2”,“3”和“4”的ascii值
答案 2 :(得分:0)
正如Rohit指出的那样,你正在利用char
类型作为数字类型。
您可以将“列表”声明为char[]
,它应该修复它,或使用数字文字。