實現:遞歸思路實現二分查找,找到返回下標,否則返回-1.
思路:思路是將查找值與數組最中間值比較,若查找值相等數字最中間值就找到了,返回下標值;若查找值小於最中間值,則把最左邊到中間作為一個數組再進行查找;若查找值大於最中間值,則把中間到最右邊作為一個數組再進行查找.
1 public class ArrayDemo{ 2 //參數a 代表查找的數組,參數left代表數組的最左邊值的下標,參數right代表數組的最右邊值的下標,參數n代表的是查找值 3 public static int binarySearch(int[] a,int left,int right,int n){ 4 //若左邊值的下標大於最右邊的下標,即代表查找完畢,沒有找到該值,返回-1 5 if(left>right){ 6 return -1; 7 } 8 int mid = (left+right)/2; 9 if(a[mid] == n){ 10 return mid; 11 }else if(a[mid] > n){ 12 return binarySearch(a,left,mid-1,n); 13 }else{ 14 return binarySearch(a,mid+1,right,n); 15 } 16 } 17 18 public static void main(String[] args) { 19 int[] a = {1,2,5,7,9}; 20 System.out.println(" " + binarySearch(a,0,a.length-1,3)); 21 } 22 }