二分查找法(binary search)也称为折半查找法,用来查找一组有序的记录数组中的某一记录,其基本思想是:将记录按有序化(递增或递减)排列,在查找过程中如果要找的元素值小于该中点元素,则将待查序列缩小为左半部分,否则为右半部分。通过一次比较,将查找区间缩小一半。
php实现二分查找算法: 1 <?php 2 $arr = array(10,15,18,21,23,24,28);
3 function binarySearch($arr,$value){ 4 $low=0; 5 $high = sizeof($arr)-1; 6 while($low<=$high){ 7 $mid = ceil(($low+$high)/2); 8 if($arr[$mid]>$value){ 9 $high = $mid-1; 10 }elseif($arr[$mid]<$value){ 11 $low = $mid+1; 12 }else{ 13 return $mid; 14 } 15 } 16 return -1; 17 }
18 19 echo binarySearch($arr,24); 20 ?>
java实现:
/*基于有序表的折半查找法*/ public class SearchFile{ public static int search(int a[],int e){ int low =0,high=a.length-1; while(low<=high){ int mid=(low+high)/2; if(e==a[mid]){ //如果在mid位置找到就返回 return mid; }else{ if(e>a[mid]){ low=mid+1; //将中位的下一位指针赋给low }else{ high=mid-1;//将中位的前一位指针赋给high } } } return -1; } public static void main(String args[]){ int a[]={1,2,3,3,4,5,5,6,7,8,9,523,3400,5600}; int index=search(a,523); System.out.println(index); } }