package com.shujia.day12;
import java.util.Arrays;
/*
Arrays: 是java提供专门针对数组做操作的工具类,该类没有构造方法,且方法都是静态的
成员方法:
public static String toString(int[] a) 将任意一个数组中的所有元素以字符串的形式拼接返回
public static void sort(int[] a) 对数组元素进行排序
public static int binarySearch(int[] a,int key) 二分查找元素,如果要保证结果正确的话,被查找的数组必须是有序的
*/
public class ArraysDemo1 {
public static void main(String[] args) {
// int[] arr = {11,22,33,44};
//// System.out.println(Arrays.toString(arr));
// String s1 = Arrays.toString(arr); // 底层其实就是使用StringBuilder对数组中元素做拼接
// System.out.println(s1);
// int[] arr2 = {32,1,53,16,73,12};
// String[] arr3 = {"apple","hadoop","java","hello","redis"}; //也可以对字符串元素数组进行排序,方式是字典顺序
// String[] arr4 = {"数加","陈真","魏一民","阿刁","东皇太一","镜","Σ(っ °Д °;)っ"};
// System.out.println("排序前:"+Arrays.toString(arr4));
// Arrays.sort(arr2);
// System.out.println("排序后:"+Arrays.toString(arr2));
//public static int binarySearch(int[] a,int key) 二分查找元素,如果要保证结果正确的话,被查找的数组必须是有序的
// int[] arr2 = {32,1,53,16,73,12};
// Arrays.sort(arr2);
//排序后:[1, 12, 16, 32, 53, 73]
// int index = Arrays.binarySearch(arr2, 100); // -7
// System.out.println(index);
}
}
====================================================================
Arrays中的binarySearch
class Arrays{
//Arrays.binarySearch(arr2, 100)
public static int binarySearch(int[] a, int key) {
// a -- [1, 12, 16, 32, 53, 73]
// key -- 100
return binarySearch0(a, 0, a.length, key);
}
private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) {
// a -- [1, 12, 16, 32, 53, 73]
// fromIndex -- 0
// toIndex -- 6
// key -- 100
int low = fromIndex; // 0
int high = toIndex - 1; // 5
while (low <= high) {
int mid = (low + high) >>> 1; // 2 4 5
int midVal = a[mid]; // 16 53 73
if (midVal < key)
low = mid + 1; // 3 5 6
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found. // -(6+1) -> -7
}
}