Voting

: max(nine, nine)?
(Example: nine)

The Note You're Voting On

eurorusty at yahoo dot ca
5 months ago
I'm not sure why PHP doesn't provide a way to specify a binary search. Here's an example of the performance gains, for this array size, about 50x improvement using interpreted PHP. If built in, it could probably achieve around 1000x improvement, again for this array size.

<?php

// Set up sorted array
$X = array(1);
for (
$j = 1; $j < 50000; ++$j)
$X[] = $X[$j - 1] + rand(1, 6);

// Using in_array
$x = -microtime(true);
$m = 0;
for (
$j = 0; $j < 10000; ++$j)
$m += in_array(rand(1, 175000), $X);
$x += microtime(true);
echo
$x.PHP_EOL;

// Using binarySearch
$x = -microtime(true);
$m = 0;
for (
$j = 0; $j < 10000; ++$j)
$m += binarySearch($X, rand(1, 175000));
$x += microtime(true);
echo
$x.PHP_EOL;

function
binarySearch($array, $value) {
$low = 0;
$high = count($array) - 1;
while (
$low <= $high) {
$pivot = floor(($low + $high) / 2);
if (
$array[$pivot] == $value)
return
true;
if (
$value < $array[$pivot])
$high = $pivot - 1;
else
$low = $pivot + 1;
}
// No match
return false;
}

/* Sample outputs, first is in_array, second is binarySearch
1.3544600009918
0.026464939117432

1.6158990859985
0.033976078033447

1.5184400081635
0.026461124420166
*/

<< Back to user notes page

To Top