1、折半查找又称为二分查找,仅适用于有序的顺序表。
class BinarySearch{ public int search(int[] a,int k){ int low = 0; int high = a.length-1; int mid; while (low <= high){ mid = (low+high)/2; if (a[mid] == k){ return mid; }else if (a[mid] > k){ high = mid -1; }else { low = mid +1; } } return -1; } }
2、测试
int[] a={7,10,13,16,33}; BinarySearch binarySearch = new BinarySearch(); int i = binarySearch.search(a, 33); System.out.println(i);
标签:折半,int,mid,BinarySearch,查找,low From: https://www.cnblogs.com/jixian/p/17174330.html