PHP实现的折半查询算法示例

yipeiwu_com5年前PHP代码库

本文实例讲述了PHP实现的折半查询算法。分享给大家供大家参考,具体如下:

什么是折半查询算法?具体文字描述自己百度。直接上代码:

<?php
header("Content-type: text/html; charset=utf-8");
/* 折半查询算法--不用递归 */
function qSort($data = array(), $x = 0){
 $startIndex = 0;    // 开始索引
 $endIndex = count($data) - 1; // 结束索引
 $index = 0;
 $number = 0;     // 计数器
 do{
  if($endIndex > $startIndex){
   $searchIndex = ceil(($endIndex - $startIndex) / 2);
  }else if($endIndex == $startIndex){
   $searchIndex = $endIndex;
  }else{
   $index = -1;
   break;
  }
  $searchIndex += ($startIndex - 1);
  echo '检索范围:'.$startIndex.' ~ '.$endIndex.'<br>检索位置:'.$searchIndex.'检索值为:'.$data[$searchIndex];
  echo '<br>=======================<br><br>';
  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.'<br>检索位置:'.$searchIndex.'检索值为:'.$data[$searchIndex];
 echo '<br>=======================<br><br>';
 if($data[$searchIndex] == $x){
  return $searchIndex;
 }else if($x > $data[$searchIndex]){
  $startIndex = $searchIndex + 1;
  return sSort($data, $x, $startIndex, $endIndex);
 }else{
  $endIndex = $searchIndex - 1;
  return sSort($data, $x, $startIndex, $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, 11, 0, count($data) - 1); // 使用递归的排序方法
echo '结果:'.$index;

运行结果:

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP数据结构与算法教程》、《PHP基本语法入门教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》及《php程序设计算法总结

希望本文所述对大家PHP程序设计有所帮助。

相关文章

使用PHP遍历文件夹与子目录的函数代码

使用PHP遍历文件夹与子目录的函数代码

我们要使用的函数有 Scandir,它的作用是列出指定路径中的文件和目录,就像 Dir 一样。 > 与更强力的 Glob() 函数,作用是以数组的形式返回与指定模式相匹配的文件名...

php递归创建目录的方法

本文实例讲述了php递归创建目录的方法,分享给大家供大家参考。 具体实现代码如下: <?php function mk_dir($path){ //第1种情况,该目录...

PHP Session变量不能传送到下一页的解决方法

我认为,出现这个问题的原因有以下几点: 1、客户端禁用了cookie 2、浏览器出现问题,暂时无法存取cookie 3、php.ini中的session.use_trans_sid =...

PHP 在5.1.* 和5.2.*之间 PDO数据库操作中的不同之处小结

介绍 今天发现php5.1.*和php5.2.*在数据库预编译代码执行的时候出现差异。 预编译优点 1.使用占位符,避免逐字输入数据到SQL中。自动处理引号和反斜线等字符的转义——增加安...

PHP创建文件及写入数据(覆盖写入,追加写入)的方法详解

本文实例讲述了PHP创建文件及写入数据(覆盖写入,追加写入)的方法。分享给大家供大家参考,具体如下: 这里主要介绍了PHP创建文件,并向文件中写入数据,覆盖,追加的实现代码,需要的朋友可...