"Basic Algorithm"
Suppose you have an array, you need to find out where the value is in the array.
?
Two-point Search
function Bin_sch ($array, $low, $high, $k) {
if ($low <= $high) {
$mid = Intval (($low + $high)/2);
if ($array [$mid] = = $k) {
return $mid;
}elseif ($k < $array [$mid]) {
Return Bin_sch ($array, $low, $mid-1, $k);
}else{
Return Bin_sch ($array, $mid +1, $high, $k);
}
}
return-1;
}
Sequential Lookup
function Seq_sch ($array, $n, $k) {
$array [$n] = $k;
for ($i =0; $i < $n; $i + +) {
if ($array [$i]== $k) {
Break
}
}
if ($i < $n) {
return $i;
}else{
return-1;
}
}
?>
Test code:
The Array.txt file contains 1 million data such as 2,3,4,5, which is determined by sequential lookup and binary lookup.
Two-point Search
<?php
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 ";
?>
Above output: Process time:0/s
Sequential Lookup
<?php
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 ";
?>
Above output: Process time:9/s
It's easy to see who's high in efficiency.
"Algorithmic Improvement"
;?
//Two-point lookup (recursive elimination)
function Bin_sch ($array, $n, $k) {
$low = 0;
$high = $n-1;
while ($low <= $high) {
$mid = intval ($high-$ Low)/2);
if ($array [$mid] = = $k)
return $mid;
ElseIf ($k < $array [$mid]) {
$high = $mid-1;
}else{
$low = $mid + 1;
}
}
return-1;
}
Sequential lookup (Improved version)
function Seq_sch ($array, $n, $k) {
$array [$n] = $k;
for ($i =0; $i + +) {
if ($array [$i]== $k) {
Break
}
}
if ($i < $n) {
return $i;
}else{
return-1;
}
}
?>
Can you see how the above two functions have changed? How much efficiency has been raised?