Binary search 二分查詢(java)
二分查詢
二分查詢可能是最常見的筆試考題之一
package binarySearchDemo;
import java.util.Scanner;
public class binary_search {
public static void main(String[] args) {
Integer [] arr = new Integer [] {2,4,6,8,10,12,14,16,18};
Scanner scan = new Scanner(System.in) ;
System.out.println("請輸入一個數");
int key = scan.nextInt() ;
System.out.println(arr[binary_search1(arr,key)]);
System.out.println("地址角標是"+binary_search1(arr,key));
}
static int binary_search1(Integer [] arr,int k){
int key = k ;
//定義 兩端角標
int low = 0 ;
int high = arr.length-1 ;
while (low<=high) {
int mid = low+high>>>1 ;//一定要放在迴圈裡面 因每次判斷都要更新mid
if(arr[mid] == key){
return mid ;
}else if (key < arr[mid]){
high = mid-1 ;
//給定值<中間結果值 說明所要查詢的在陣列的左半部 又因mid位置數字不相等 所以high = mid-1
}else if (key>arr[mid]){
low = mid+1 ;
}
}
return -1;
}
}