今天学的头疼,有些地方还是要自己深入的琢磨琢磨。虽然java是面向对象的,过程也是要稍微掌握点的。
在使用这个方法的时候,譬如:
static int | binarySearch(int[] a, int key) Searches the specified array of ints for the specified value using the binary search algorithm. |
import study.Arrays2;
import java.util.*;
public class ArraySearching {
public static void main(String[] args) {
int[] a = new int[5];
Arrays2.RandIntGenerator gen = new Arrays2.RandIntGenerator(1000);
Arrays2.fill(a,gen);
Arrays.sort(a);
System.out.println("Sorted array: " + Arrays2.toString(a));
while(true) {
int r = gen.next();
int location = Arrays.binarySearch(a,r);
System.out.println(r);
System.out.println(location);
if(location >= 0) {
System.out.println("Location of " + r + " is " + location + ", a[" + location + "] = " + a[location]);
break;
}
}
}
}
如果数组a中如果没有key,则返回值为某个负值,表示为了保持排序状态,此目标元素应该插入的位置“-(插入点)-1”;如果找到了key,则返回key所在元素下标。
插入点是指,第一个大于查找对象的元素在数组中的位置,如果数组所有元素都小于要查找的对象,插入点就等于a.size().