Most efficient way to search a sorted matrix?

后端 未结 9 1519
野的像风
野的像风 2020-12-29 14:02

I have an assignment to write an algorithm (not in any particular language, just pseudo-code) that receives a matrix [size: M x N] that is sorted in a way that all of it\'s

9条回答
  •  情话喂你
    2020-12-29 14:28

    JavaScript solution:

    //start from the top right corner
    //if value = el, element is found
    //if value < el, move to the next row, element can't be in that row since row is sorted
    //if value > el, move to the previous column, element can't be in that column since column is sorted
    
    function find(matrix, el) {
    
      //some error checking
      if (!matrix[0] || !matrix[0].length){
        return false;
      }
      if (!el || isNaN(el)){
        return false;
      }
    
      var row = 0; //first row
      var col = matrix[0].length - 1; //last column
    
      while (row < matrix.length && col >= 0) {
        if (matrix[row][col] === el) { //element is found
          return true;
        } else if (matrix[row][col] < el) {
          row++; //move to the next row
        } else {
          col--; //move to the previous column
        }
      }
    
      return false;
    
    }
    

提交回复
热议问题