要使用二分法需要注意: 数组中的元素必须已经按升序排列好
二分法主要思想是将一个数组一分为二,每次查询都能将查询范围在上一次的基础上缩小一半。所以效率非常高。
下面是Java代码实现:
import java.util.*; public class Main { public static void main(String[] args) throws Exception { Integer[] numbers = new Integer[] { 1,3,2,1,2,3,2,7,7,8,2 }; Integer target = 7; Integer head = 0; Integer tail = numbers.length - 1; Integer middle = (head + tail)/2; Arrays.sort(numbers); for(Integer item : numbers) System.out.print(item + " "); System.out.println(); Integer targetIndex = dichotomySearch(numbers,head,middle,tail,target); if(targetIndex == null) System.out.println("target not found"); else System.out.println("target in: " + targetIndex); } public static Integer dichotomySearch(Integer[] numbers,Integer head, Integer middle,Integer tail,Integer target) { //System.out.println("head:" + head + " middle:" + middle + " tail:" + tail); if(target.equals(numbers[head])) return head; if(target.equals(numbers[middle])) return middle; if( target.equals(numbers[tail])) return tail; if(head.equals(middle) || head.equals(tail)||middle.equals(tail)) return null; if(target.compareTo(numbers[head]) > 0 && target.compareTo(numbers[middle]) < 0) { System.out.println("A"); tail = middle; middle = (head + tail)/2; } else if(target.compareTo(numbers[middle]) > 0 && target.compareTo(numbers[tail]) < 0) { head = middle; middle = (head + tail)/2; } else { return null; } return dichotomySearch(numbers, head, middle, tail, target); } }
输出结果:
1 1 2 2 2 2 3 3 7 7 8
target in: 8