Heim  >  Artikel  >  Backend-Entwicklung  >  二分查找PHP实现

二分查找PHP实现

WBOY
WBOYOriginal
2016-07-25 08:46:12811Durchsuche
  1. /**二分查找:查找一个值在数组中的位置
  2. * @$arr:操作的数组,前提是按顺序排列
  3. * @$val:查找的值
  4. * @$low:查找的起始位置,默认从数组的第一个数找起
  5. * @hight:查找的结束位置
  6. **/
  7. function binarySearch($arr, $val, $hight, $low=0){
  8. while($low $mid = ceil($low + ($hight - $low) / 2);
  9. if($arr[$mid] == $val){
  10. return $mid;
  11. }elseif($arr[$mid] > $val){
  12. $hight = $mid -1;
  13. }else{
  14. $low = $mid +1;
  15. }
  16. }
  17. return -1;
  18. }
  19. header('Content-Type:text/html; charset=utf-8');
  20. //产生一个数组
  21. $arr = range(0,20);
  22. echo '
    ';
  23. print_r($arr);
  24. echo '';
  25. $low = 0;
  26. $hight = count($arr) - 1;
  27. $findVal = rand(0, 20);
  28. $index = binarySearch($arr, $findVal, $hight, $low);
  29. printf("查找的值 '%d' 在数组中的下标 '%s'", $findVal, $index);
  30. ?>
复制代码

PHP


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn