Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

quickest scan for match in an array 1

Status
Not open for further replies.

thedaver

IS-IT--Management
Jul 12, 2001
2,741
US
Knowing that the most efficient or quickest method is not always obvious... I ask:

with an array of
Code:
$array=array("a","b","c","d");
How do I efficiently/quickly determine if the string "c" is an exact member of an array of strings or not?

Current contender is:
Code:
$found=0;
$array=array("a","b","c","d");
$matchme="c";
foreach ($array as $a) {
  if ($a == $matchme) { $found=1; break; }
}
if ($found) {.......}

Thoughts on doing better? Obvious penalty now is matching at the end of the array takes "longer".


D.E.R. Management - IT Project Management Consulting
 
If your array elements are in order, you want to write your own loop and add:
Code:
if ($a < $matchme) { $found=1; break; }

This really speeds up when $a would be close to the beginning of the array.

You can also reduce the number of checks against an array in order (of size n) by checking against the center element (n/2), then against n/4 or 3n/4 depending on if the new element is larger or smaller than the n/2 element. And so on until you've found your element or your search range has basically vanished and not found it. Pseudocode:

Code:
boolean findArray( Array<Object> myarray, Object find, int low, int high )
{
   center = (high + low) / 2
   if find = myarray[center]
      return true ;
   if find < myarray[center]
      if low = find
         return false ;
      return findArray( myarray, find, low, center - 1 )
   if find > myarray[center]
      if high = find
         return false ;
      return findArray( myarray, find, center + 1, high )
}


 
I'm pretty certain that interpreted PHP code is not going to be faster than a compiled builtin PHP function. More efficient, possibly, but I strongly doubt faster.

From a somewhat cursory look at the PHP source code, it appears to me that PHP generates hashes of the contents of the elements of arrays and performs searches against those hashes. That would improve the efficiency of the builtin function.



Want the best answers? Ask the best questions! TANSTAAFL!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top