二分查找易错和模板
Java的二分查找源码
1 | public static int binarySearch(int[] a, int key) { |
易错:必须加“=”
while循环里必须是low <= high,如果没有“=”,比如查找数组[3,4]中的4
low=0,high=1,mid=0
a[mid]=3<4
low=mid+1=1
导致循环直接结束而没有找到4
1 | public static int binarySearch(int[] a, int key) { |
while循环里必须是low <= high,如果没有“=”,比如查找数组[3,4]中的4
low=0,high=1,mid=0
a[mid]=3<4
low=mid+1=1
导致循环直接结束而没有找到4