Java程序在float数组上实现二进制搜索
可以使用java.util.Arrays.binarySearch()方法实现对float数组的二进制搜索。如果所需的float元素在数组中可用,则此方法返回其索引,否则返回(-(插入点)-1),其中插入点是将元素插入数组的位置。
演示此的程序如下所示-
示例
import java.util.Arrays;
public class Demo {
public static void main(String[] args) {
float f_arr[] = { 5.2f, 9.5f, 6.5f, 2.8f, 3.6f };
Arrays.sort(f_arr);
System.out.print("The sorted array is: ");
for (float i : f_arr) {
System.out.print(i + " ");
}
System.out.println();
int index1 = Arrays.binarySearch(f_arr, 6.5f);
System.out.println("The float value 6.5 is at index " + index1);
int index2 = Arrays.binarySearch(f_arr, 7.5f);
System.out.println("The float value 7.5 is at index " + index2);
}
}输出结果
The sorted array is: 2.8 3.6 5.2 6.5 9.5 The float value 6.5 is at index 3 The float value 7.5 is at index -5
现在让我们了解上面的程序。
定义了浮点数组f_arr[],然后使用Arrays.sort()对其进行了排序。然后使用for循环打印排序后的数组。演示这的代码片段如下-
float f_arr[] = { 5.2f, 9.5f, 6.5f, 2.8f, 3.6f };
Arrays.sort(f_arr);
System.out.print("The sorted array is: ");
for (float i : f_arr) {
System.out.print(i + " ");
}
System.out.println();方法Arrays.binarySearch()用于查找元素6.5和7.5的索引。由于数组中有6.5,因此将显示其索引。另外,数组中没有7.5,因此显示根据(-(插入点)-1)的值。演示这的代码片段如下-
int index1 = Arrays.binarySearch(f_arr, 6.5f);
System.out.println("The float value 6.5 is at index " + index1);
int index2 = Arrays.binarySearch(f_arr, 7.5f);
System.out.println("The float value 7.5 is at index " + index2);热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便