public class BinSearch { //遞歸實現 public static int binSearch(int[]arr,int low,int high,int key){ if(low>high||key<arr[low]||key>arr[high]){ return -1 ; } int mid = low+(high-low) / 2; if (arr[mid] < key) { return binSearch(arr, mid + 1, high, key); } else if (arr[mid] > key) { return binSearch(arr, low, mid - 1, key); } else { return mid; } } //非遞歸循環實現 public static int binSearch1(int[]arr,int key){ int low=0; int high=arr.length-1; while(low<=high){ int mid=low+(high-low)/2; if(arr[mid]>key){ low=mid+1; }else if(arr[mid]<key){ high=mid-1; }else{ return mid; } } return -1; } public static void main(String[] args) { int[] arr=new int[]{3,4,5,6,7,8}; System.out.println(binSearch(arr,0,arr.length-1,5)); System.out.println(binSearch1(arr,5)); } }