How to check if a given row is sorted in a matrix with PHP

2 Answers

0 votes
function isRowSorted($matrix, $row) {
    $cols = count($matrix[0]);
    
    for ($i = 1; $i < $cols; $i++) {
        if ($matrix[$row][$i - 1] > $matrix[$row][$i]) {
            return false;
        }
    }
    return true;
}

$matrix = array(
            array( 4,  7,  9, 12), 
            array( 1,  8,  3,  4), 
            array(-9, -4, -3,  2), 
            array(-8, -3, -9,  4), 
            array( 2,  6,  7, 18)
        );
        
echo "Row 0: " . isRowSorted($matrix, 0) . "\n";
echo "Row 1: " . isRowSorted($matrix, 1) . "\n";
echo "Row 2: " . isRowSorted($matrix, 2) . "\n";
echo "Row 3: " . isRowSorted($matrix, 3) . "\n";
echo "Row 4: " . isRowSorted($matrix, 4) . "\n";



/*
run:

Row 0: 1
Row 1: 
Row 2: 1
Row 3: 
Row 4: 1

*/

 



answered Jun 23, 2023 by avibootz
0 votes
function isRowSorted($matrix, $row) {
    $cols = count($matrix[0]);
    
    $sorted = array_values($matrix[$row]);
    sort($sorted);

    return $matrix[$row] === $sorted;
}
 
$matrix = array(
            array( 4,  7,  9, 12), 
            array( 1,  8,  3,  4), 
            array(-9, -4, -3,  2), 
            array(-8, -3, -9,  4), 
            array( 2,  6,  7, 18)
        );
         
echo "Row 0: " . isRowSorted($matrix, 0) . "\n";
echo "Row 1: " . isRowSorted($matrix, 1) . "\n";
echo "Row 2: " . isRowSorted($matrix, 2) . "\n";
echo "Row 3: " . isRowSorted($matrix, 3) . "\n";
echo "Row 4: " . isRowSorted($matrix, 4) . "\n";
 

 
 
/*
run:
 
Row 0: 1
Row 1: 
Row 2: 1
Row 3: 
Row 4: 1
 
*/

 



answered Jun 25, 2023 by avibootz

Related questions

1 answer 128 views
2 answers 168 views
1 answer 131 views
1 answer 132 views
1 answer 147 views
...