Java學習筆記30:二分查詢演算法程式碼
阿新 • • 發佈:2019-01-05
package create; public class Demo1_Array { public static void main(String[] args){ int[] arr = {11,22,33,44,55,66,77}; System.out.println(getIndex(arr,22)); System.out.println(getIndex(arr,77)); System.out.println(getIndex(arr,88)); } public static int getIndex(int[] arr,int value){ int min=0; int max=arr.length-1; int mid; while(min<=max){ mid=(max+min)/2; if(arr[mid]==value){ return mid; }else if(arr[mid]<value){ min=mid+1; }else{ max=mid-1; } } return -1; } } //以下程式碼有誤 /*while(arr[mid]!=value){//中間值不等於所求值,開始迴圈查詢 if(arr[mid]<value){ min=mid+1; }else if(arr[mid]>value){ min=mid-1; } mid=(min+max)/2; if(min>max){ return -1; } }//while結束 return mid; */