Java 数组排序和折半查找:使用 Arrays 类
import java.util.Arrays; import java.util.Scanner;
public class Main { public static void main(String[] args) { double a[] = {12, 34, 9, -23, 45, 6, 90, 123, 19, 45, 34}; Arrays.sort(a); // 对数组进行升序排序
System.out.print("请输入一个整数:");
Scanner scanner = new Scanner(System.in);
int target = scanner.nextInt();
int index = Arrays.binarySearch(a, target); // 使用折半查找在数组中查找目标整数的索引位置
if (index >= 0) {
System.out.println("数组中存在该整数,索引位置为:" + index);
} else {
System.out.println("数组中不存在该整数");
}
}
}
原文地址: https://www.cveoy.top/t/topic/pdjZ 著作权归作者所有。请勿转载和采集!