可以使用java.util.Arrays.binarySearch()方法实现对char数组的二进制搜索。如果所需的char元素在数组中可用,则此方法返回其索引,否则,返回(-(插入点)-1),其中插入点是元素将在数组中插入的位置。
演示此的程序如下所示-
import java.util.Arrays; public class Demo { public static void main(String[] args) { char c_arr[] = { 'b', 's', 'l', 'e', 'm' }; Arrays.sort(c_arr); System.out.print("The sorted array is: "); for (char i : c_arr) { System.out.print(i + " "); } System.out.println(); int index1 = Arrays.binarySearch(c_arr, 'e'); System.out.println("The character e is at index " + index1); int index2 = Arrays.binarySearch(c_arr, 'z'); System.out.println("The character z is at index " + index2); } }
输出结果
The sorted array is: b e l m s The character e is at index 1 The character z is at index -6
现在让我们了解上面的程序。
定义字符数组c_arr [],然后使用Arrays.sort()对其进行排序。然后使用for循环打印排序后的数组。演示这的代码片段如下-
char c_arr[] = { 'b', 's', 'l', 'e', 'm' }; Arrays.sort(c_arr); System.out.print("The sorted array is: "); for (char i : c_arr) { System.out.print(i + " "); } System.out.println();
Arrays.binarySearch()方法用于查找元素“ e”和“ z”的索引。由于“ e”在数组中,因此将显示其索引。另外,“ z”不在数组中,因此显示根据(-(插入点)-1)的值。演示这的代码片段如下-
int index1 = Arrays.binarySearch(c_arr, 'e'); System.out.println("The character e is at index " + index1); int index2 = Arrays.binarySearch(c_arr, 'z'); System.out.println("The character z is at index " + index2);