折半查找(二分查找)

接下来记录下几个有意思的查找算法: 折半查找,也叫二分查找,该算法有个前提,就是数组元素要有序 主要思路是:每次比较中间那个值;每完成一次比较,范围缩小一般public class BinarySearch {public static void main(String[] args){int[] a = {1,3,5,7,9,11,13,15,17}; binarySearch(a, 1); }private static int binarySearch(int[] a, int key){ int count = 0; int low = 0; int high = a.length-1; int mid; while(low <= high){ mid = (low + high)/2; count++; if(a[mid] == key){ System.out.println("比较次数:" + count); return mid; }else if(a[mid] > key){ high = mid -1; }else{ low = mid + 1; } } return -1; } }

结果:
比较次数:3
【折半查找(二分查找)】

    推荐阅读