/** * search_seq ($arr, $elem): Order lookup * search_seq2 ($arr, $elem): Sequential lookup (optimization) * search_ Bin ($arr, $elem): Binary find * searchbst ($elem): two forks search */class search{ public $arr; function __construct ($arr) { $this->arr = $arr; } /** * Sequential Find * @param $arr in $arr Array Find * @param $elem Find if there is an element $elem in the array, the position returned in the array, or 0 */ public static function search_seq ($arr, $elem) { for ($i =0; $i <count ($arr); $i +) { if ($arr [$i]== $elem) { return $i; } } return 0; } //This algorithm is an optimization of the above algorithm &NBSP;PUBLIC&NBSP;STATIC&NBSP;FUNCTION&NBSP;SEARCH_SEQ2 ($arr, $elem) { $i =0; while ($arr [$i]!= $elem) { $i ++; } return $i; } /** * Binary lookup (also called binary lookup), provided the array must be ordered-from small to large * @ param $arr Find in the $arr array * @param $elem Find out if there are elements in an array Elem, with the position returned in the array, or 0&NBsp; */ public static function search_bin ($arr, $ Elem) { $low =0; $ High=count ($arr); while ($low <= $high) { $mid =round (($low + $high)/2);// $mid = $low + ($low + $high) * ($elem-$arr [$low])/($arr [$high]-$arr [$ Low]); //If you change the value of $mid to this sentence, it becomes an interpolation lookup. This finding algorithm is more efficient than binary when the data size distribution is more uniform. if ($elem < $arr [$mid]) { $high = $mid -1; }else if ($elem > $arr [$mid]) { $low = $mid +1; }else{ return $ mid; } } return 0; } /** * Two fork sort tree * @ param $elem * @return int */ public function searchbst ($elem) { return $this->find ($this->arr[0], $elem, 0); } private Function find ($root, $elem, $i) { if ($i >count ($this ARR) | | ! $root) { return ' Error '; } if ($elem = = $root) { return $i; } if ($elem < $root && $i +1<count ($this->arr)) { return $this->find ($this->arr[$i *2+1], $elem, $i *2+1); }else if ($elem > $root && $i *2+2<count ($this->arr) { return $this->find ($this->arr[$i *2+2],$ Elem, $i *2+2); } Return 0; &nBSP;}}
This article is from the "Everything Possible" blog, please be sure to keep this source http://noican.blog.51cto.com/4081966/1610884
Data structure Lookup (PHP code implementation)