本文實例講述了PHP實現二維數組中的查找算法。分享給大家供大家參考,具體如下:
方法1:silu從左下角最后一行的第一個元素開始,遍歷。如果小于target 則遍歷該行的所有元素,找到結束。如果大于繼續往上一行進行。等于直接結束。
<?php function Find($target, $array) { $m_y = count($array['0']); $m_x = count($array); for($i=$m_x-1;$i>=0;$i--){ if($array[$i]['0'] < $target){ for($j=1;$j<$m_y;$j++){ if($array[$i][$j] == $target){ return 1; break; } } } if($array[$i]['0'] == $target){ return 1; break; } } }
方法2:
function Find($target, $array) { $m_y = count($array['0']); $m_x = count($array); $i = 0; for($i =$m_x-1,$j=0;$i>=0&&$j<$m_y;){ if($array[$i][$j]<$target){ $j++; continue; } if($array[$i][$j]>$target){ $i--; continue; } if($array[$i][$j] == $target){ return 1; } } }
方法3:
function Find($target, $array) { $m_y = count($array['0']); $m_x = count($array); $i = $m_x-1; $j = 0; while(1){ if($array[$i][$j]<$target){ $j++; } if($array[$i][$j]>$target){ $i--; } if($array[$i][$j] == $target){ return 1; } if($i == 0||$j == $m_y-1){ return 0; } } }
希望本文所述對大家PHP程序設計有所幫助。