二分查找法(binary search)也稱爲折半查找法,用來查找一組有序的記錄數組中的某一記錄,其基本思想是:將記錄按有序化(遞增或遞減)排列,在查找過程當中若是要找的元素值小於該中點元素,則將待查序列縮小爲左半部分,不然爲右半部分。經過一次比較,將查找區間縮小一半。php
php實現二分查找算法: 1 <?php 2 $arr = array(10,15,18,21,23,24,28);java
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); } }