中午閒着有點時間,作個demo睡覺去,這個例子網上應該都有,本身只是敲一下給本身作個記錄。數組
public static void main(String[] args) {code
int[] whitelist = new int[]{12,13,34,56,78,88,99,100};
Arrays.sort(whitelist);
Scanner sc = new Scanner(System.in);blog
boolean go=true;
while(true)
{
System.out.println("請輸入要查找的數");
int nextInt = sc.nextInt();it
sc.nextLine();
int result = rank(nextInt,whitelist);
if(result!=-1)
{
System.out.println("找到的數字位置爲:"+result);
go=false;
}
else
{
System.out.println("沒有找到輸入的數字位置");
}
}
}class
public static int rank(int key, int[] a) {
// 數組必須是有序的
int lo = 0;
int hi = a.length - 1;
while (lo <= hi) {
// 被查找的鍵要麼不存在,要麼必然存在於a[lo,hi]之間
int mid = lo + (hi - lo) / 2;
if (key < a[mid]) {
hi = mid - 1;
} else if (key > a[mid]) {
lo = mid + 1;
} else {
return mid;
}next
}demo
return -1;
}sort