标签:int [] logs search 有序 下标 class static color
1 public static String binarySearch(int[] a, int num) { 2 if (a.length == 0) 3 return "Eroor"; 4 int start = 0; 5 int end = a.length - 1; 6 int mid = (start + end) / 2; 7 while (start <= end) { 8 if (num == a[mid]) { 9 return "所查数在数组的下标为" + mid; 10 } else if (num > a[mid]) { 11 start = mid + 1; 12 } else if (num < a[mid]) { 13 end = mid - 1; 14 } 15 mid = (start + end) / 2; 16 } 17 return "数组中无该数值"; 18 }
递归实现:
public static String binarySearch(int[] arr, int num,int start,int end) { if (arr.length == 0 || end<start) return "Eroor"; int mid = (start + end) / 2; if (num==arr[mid]) { return "所查数在数组的下标为"+mid; }else if(num<arr[mid]) { return binarySearch(arr, num,start,mid-1); }else { return binarySearch(arr, num, mid+1, end); } }
标签:int [] logs search 有序 下标 class static color
原文地址:http://www.cnblogs.com/littlewriter/p/6645564.html