public class BinarySearch { public static int search(int[] a, int k) { int index = -1; int low = 0; int high = a.length-1; while(low<high) { int mid = low + (high-low)/2; if(k==a[mid]) { index = mid; break; } else if( k<a[mid] ) { high = mid-1; } else { low = mid+1; } } return index; } public static int searchRecursive(int[] a, int k, int p, int q) { int m = p + (q-p)/2; if(k==a[m]) return m; if(p==q) return -1; if(k<a[m]) //search left return searchRecursive(a, k, p, m); return searchRecursive(a, k, m+1, q); } public static void main(String[] args) { int[] a = {1,2,3,4,5,6,7,8}; int index = search(a, 7); if(index!=-1) System.out.printf(“index=%d/n”,index); else System.out.println(“Not found!”); } }
Java二分法(Binary Search)查找递归算法与迭代算法
原文作者:查找算法
原文地址: https://blog.csdn.net/huoyin/article/details/6059199
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/huoyin/article/details/6059199
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。