今天學的頭疼,有些地方還是要自己深入的琢磨琢磨。雖然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().