gpt4 book ai didi

java - 如果找到特定数字,如何使该打印正确或错误?

转载 作者:行者123 更新时间:2023-12-01 23:02:55 25 4
gpt4 key购买 nike

我想做一个二分搜索来找到我的数字 arraylist 并在找到时打印 false 或 true?

我希望我的 targetValues 看看它们是否存在于 arr 列表中并打印 true 或 false

public static void main(String[] args) throws IOException {


{

int arr[] = {10,20,30,40};
int targetValue[]= {10,25,40}
}

}

这是我的二分搜索代码

    public static boolean binarySearch(int[] arr, int n) {
int first = 0;
int last = arr.length-1;
int mid;
while (first <= last){
mid = first + (last - first) / 2;
if (n == arr[mid]) return true;
else if (n < arr[mid]) last = mid - 1;
else first = mid + 1;
}
return false;

}

最佳答案

假设您的数组按升序排序,这应该可行:

    public static void main(String[] args) throws IOException {
{
int arr[] = {10, 20, 30, 40};
int targetValue[] = {10, 25, 40};
int index = 0;
while (index < targetValue.length) {
out.println("Search for " + targetValue[index] + " " + binarySearch(arr, targetValue[index]));
index++;
}

}
public static boolean binarySearch(int[] arr, int n) {
int count = 0;
int mid = (arr.length - 1) / 2;
while (count < arr.length - 1) {
if (n == arr[mid]) {
return true;
} else if (n < arr[mid]) {
if (mid != 0) {
mid = mid - 1;
} else {
return false;
}
} else {
if (mid != arr.length - 1) {
mid = mid + 1;
} else {
return false;
}
}
count++;
}
return false;
}

关于java - 如果找到特定数字,如何使该打印正确或错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58415267/

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