本文实例讲述了PHP实现的折半查询算法。分享给大家供大家参考,具体如下:
rush:PHP;">
$startIndex){
$searchIndex = ceil(($endindex - $startIndex) / 2);
}else if($endindex == $startIndex){
$searchIndex = $endindex;
}else{
$index = -1;
break;
}
$searchIndex += ($startIndex - 1);
echo '检索范围:'.$startIndex.' ~ '.$endindex.'
检索位置:'.$searchIndex.'检索值为:'.$data[$searchIndex]; echo '
=======================
'; if($data[$searchIndex] == $x){ $index = $searchIndex; break; }else if($x > $data[$searchIndex]){ $startIndex = $searchIndex + 1; }else{ $endindex = $searchIndex - 1; } $number++; }while($number < count($data)); return $index; } /* 折半查询算法--使用递归 */ function sSort($data,$x,$startIndex,$endIndex){ if($endIndex > $startIndex){ $searchIndex = ceil(($endindex - $startIndex) / 2); }else if($endindex == $startIndex){ $searchIndex = $endindex; }else{ return -1; } $searchIndex += ($startIndex - 1); echo '检索范围:'.$startIndex.' ~ '.$endindex.'
检索位置:'.$searchIndex.'检索值为:'.$data[$searchIndex]; echo '
=======================
'; if($data[$searchIndex] == $x){ return $searchIndex; }else if($x > $data[$searchIndex]){ $startIndex = $searchIndex + 1; return sSort($data,$endindex); }else{ $endindex = $searchIndex - 1; return sSort($data,$endindex); } } $data = array(1,3,4,6,9,11,12,13,15,20,21,25,33,34,35,39,41,44); $index = qSort($data,11); // 不用递归的排序方法 $index = sSort($data,count($data) - 1); // 使用递归的排序方法 echo '结果:'.$index;
检索位置:'.$searchIndex.'检索值为:'.$data[$searchIndex]; echo '
=======================
'; if($data[$searchIndex] == $x){ $index = $searchIndex; break; }else if($x > $data[$searchIndex]){ $startIndex = $searchIndex + 1; }else{ $endindex = $searchIndex - 1; } $number++; }while($number < count($data)); return $index; } /* 折半查询算法--使用递归 */ function sSort($data,$x,$startIndex,$endIndex){ if($endIndex > $startIndex){ $searchIndex = ceil(($endindex - $startIndex) / 2); }else if($endindex == $startIndex){ $searchIndex = $endindex; }else{ return -1; } $searchIndex += ($startIndex - 1); echo '检索范围:'.$startIndex.' ~ '.$endindex.'
检索位置:'.$searchIndex.'检索值为:'.$data[$searchIndex]; echo '
=======================
'; if($data[$searchIndex] == $x){ return $searchIndex; }else if($x > $data[$searchIndex]){ $startIndex = $searchIndex + 1; return sSort($data,$endindex); }else{ $endindex = $searchIndex - 1; return sSort($data,$endindex); } } $data = array(1,3,4,6,9,11,12,13,15,20,21,25,33,34,35,39,41,44); $index = qSort($data,11); // 不用递归的排序方法 $index = sSort($data,count($data) - 1); // 使用递归的排序方法 echo '结果:'.$index;
运行结果:
更多关于PHP相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》及《PHP程序设计算法总结》
希望本文所述对大家PHP程序设计有所帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。