java - 如果找到特定数字,如何使此打印为真或假?
问题描述
我想进行二进制搜索以在我的数组列表中查找一个数字,如果找到它则打印 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;
}
推荐阅读
- android - 无论如何在这里访问java代码中的gradle ext属性吗?
- node.js - npm open 在服务器中部署时不起作用?
- html - 如何在导航栏中垂直对齐按钮?
- javascript - 单击按钮时的 jQuery 动画表单
- python - DJANGO HEROKU:django.db.migrations.exceptions.InconsistentMigrationHistory:
- java - Dynamodb 本地连接被 Java 拒绝
- azure - 如何在通过 ARM 模板创建部署时从系统变量中读取输入
- makefile - Makefile 动态变量作为先决条件
- c# - 停用组合框中的 SelectionChanged
- python - 将用户重定向到登录时的单独页面