Summarization of search algorithm in two dimensional array implemented by PHP

  • 2021-10-15 10:00:20
  • OfStack

In this paper, an example is given to describe the search algorithm in 2-dimensional array realized by PHP. Share it for your reference, as follows:

Method 1: silu starts with the first element in the last line in the lower left corner and traverses. If it is less than target, traverse all the elements of the row and find the end. If it is greater than 1 line ahead. Equal to direct end.


<?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;
    }
  }
}

Method 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;
      }
    }
}

Method 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;
    }
  }
}

For more readers interested in PHP related contents, please check the topics of this site: "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "php String (string) Usage Summary", "PHP Array (Array) Operation Skills Complete Book", "PHP Common Traversal Algorithms and Skills Summary" and "PHP Mathematical Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: