gpt4 book ai didi

java - 选择排序递归调用

转载 作者:行者123 更新时间:2023-12-01 17:27:29 26 4
gpt4 key购买 nike

I was studying recursion problem I was going to call it, but it shows like this

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));

}

}

output : [49, 50, 52, 53]

我应该怎样做才能使其正确?

最佳答案

您正在整数数组中存储字符:-

int [] list = {'1', '2','4','5'};

因此,您获得的值分别是 1, 2, 4, 5 的 ASCII 代码。因此,您的 binarySearch 方法将无法找到值 4。因为,它并不完全在那里。删除您的值周围的单引号。

其次,您没有打印 binarySearch 方法的返回值:-

binarySearch(list, 4);

应该是:-

System.out.println(binarySearch(list, 4));

关于java - 选择排序递归调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13764875/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com