二分查找

二分查找的实现。

算法要求

1.必须采用顺序存储结构 2.必须按关键字大小有序排列。

算法复杂度为o(logn),一般只要被查找的元素大于或等于序列中的最大元素,算法总要执行最大

次数的比较。

对于一个大小为n的排序数组,算法BINARYSEARCH执行的比较的最大次数为[logn]+1。

 1 public class BinarySearch {
 2 
 3     public static int BinarySearchMethod(int[] before,int target){
 4         int low = 0,high = before.length - 1,mid = 0,j = 0;
 5         
 6         while(low <= high&&j == 0){
 7             mid = (low+high)/2;
 8             
 9             if(target == before[mid]){
10                 return mid;
11             }else if(target < before[mid]){
12                 high = mid -1;
13             }else if(target > before[mid]){
14                 low = mid +1;
15             }
16         }
17         
18         return -1;
19     }
20     
21     public static void main(String[] args){
22         int[] before = {1,4,5,6,8,9,10,12,15,22,23}; 
23         int after = 0,target = 22;
24         
25         after = BinarySearchMethod(before,target);
26         
27         System.out.println("find:"+after);
28     }
29 }

 

原文地址:https://www.cnblogs.com/cnlixl/p/2617505.html