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动态生成静态HTML网页的代码

我们知道,PHP读取MYSQL动态显示,在访问量大的情况下,会有很多性能问题,如果租用别人的虚拟主机,则会因为CPU消耗过多而被限制CPU,导致网页无法访问。我这里给出一个PHP动态生成...

浅谈php调用python文件

浅谈php调用python文件

关于PHP调用Python数据传输问题 这是以前大学时做项目出现的问题,现在把它挪上来,希望给遇到问题的未来大佬给出一些小的思路,请大佬们不要大意的帮我改正,如果出现问题或者有更好的解决...

php判断邮箱地址是否存在的方法

PHP校验邮箱地址的方法很多, 比较常用的就是自己写正则了, 不过正则多麻烦, 我PHP自带了方法做校验。 filter_var filter_var是PHP内置的一个变量过滤的方法,...

Linux环境下搭建php开发环境的操作步骤

本文主要记载了通过编译方式进行软件/开发环境的安装过程,其他安装方式忽略! 文章背景: 因为php和Apache等采用编译安装方式进行安装,然而编译安装方式,需要c,c++编译环境, 通...

php写入、删除与复制文件的方法

本文实例讲述了php写入、删除与复制文件的方法。分享给大家供大家参考。具体如下: 1. 写入: <?php $filename = "Test//file.txt";...