标签:
要使用二分法需要注意: 数组中的元素必须已经按升序排列好
二分法主要思想是将一个数组一分为二,每次查询都能将查询范围在上一次的基础上缩小一半。所以效率非常高。
下面是Java代码实现:
1 public class DichotomySearchDemo 2 { 3 4 public static void main(String[] args)throws Exception 5 { 6 int[] array = new int[]{1,3,4,6,7,9,10,10,12,18,21,29}; 7 int head = 0; 8 int tail = array.length-1; 9 int mid = (head+tail)/2; 10 int target = 10; 11 12 dichotomySearch(array,head,mid,tail,target); 13 } 14 15 public static void dichotomySearch(int[] array,int head,int mid, int tail,int target) 16 { 17 if(array[head] == target) 18 { 19 System.out.println("目标"+target+"已找到,位置:" + head); 20 return; 21 }else if(array[mid] == target) 22 { 23 System.out.println("目标"+target+"已找到,位置:" + mid); 24 return; 25 }else if(array[tail] == target) 26 { 27 System.out.println("目标"+target+"已找到,位置:" + tail); 28 return; 29 } 30 31 if(head == mid || head == tail || mid == tail) 32 { 33 System.out.println("查找失败"); 34 return; 35 } 36 37 if(target > array[mid]) 38 { 39 head = mid; 40 } 41 else if(target < array[mid]) 42 { 43 tail = mid; 44 } 45 mid = (head + tail ) / 2; 46 47 dichotomySearch(array,head,mid,tail,target); 48 } 49 }
输出结果:
目标10已找到,位置:6
标签:
原文地址:http://www.cnblogs.com/kuillldan/p/5701338.html