【基本算法】
假设有一个数组,需要找出某个值在该数组中的位置。
//二分查找
function bin_sch($array, $low, $high, $k){
if ($low $mid = intval(($low+$high)/2);
if ($array[$mid] == $k){
return $mid;
}elseif ($k return bin_sch($array, $low, $mid-1, $k);
}else{
return bin_sch($array, $mid+1, $high, $k);
}
}
return -1;
}
//顺序查找
function seq_sch($array, $n, $k){
$array[$n] = $k;
for($i=0; $i if($array[$i]==$k){
break;
}
}
if ($i return $i;
}else{
return -1;
}
}
?>
测试代码:
array.txt 文件里面包含了一百万条类似 2,3,4,5 这样的数据,下面通过顺序查找和二分查找来确定速度。
//二分查找
set_time_limit(0);
$array = array();
$file = file_get_contents("./array.txt");
$array = explode(",", $file);
sort($array);
$st = time();
$k = 43;
$n = count($array);
$r = bin_sch($array, 0, $n-1, $k);
$et = time();
$t = $et-$st;
echo "Process time: ". $t ."/s";
?>
以上输出: Process time: 0/s
//顺序查找
set_time_limit(0);
$array = array();
$file = file_get_contents("./array.txt");
$array = explode(",", $file);
$st = time();
$k = 43;
$n = count($array);
$r = seq_sch($array, $n, $k);
$et = time();
$t = $et-$st;
echo "Process time: ". $t ."/s";
?>
以上输出结果:Process time: 9/s
上面轻易就能够看出谁的效率高了。
【算法改进】
//二分查找(递归消除)
function bin_sch($array, $n, $k){
$low = 0;
$high = $n-1;
while($low $mid = intval(($high-$low)/2);
if ($array[$mid] == $k)
return $mid;
elseif ($k $high = $mid - 1;
}else{
$low = $mid + 1;
}
}
return -1;
}
//顺序查找(改进版)
function seq_sch($array, $n, $k){
$array[$n] = $k;
for($i=0; ; $i++){
if($array[$i]==$k){
break;
}
}
if ($i return $i;
}else{
return -1;
}
}
?>
能看出上面两个函数做了什么改变吗?效率提升了多少?

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
