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

Problem overview

If you are given a mxn matrix and k, a number denoting the row number, how do you check whether the kth of the matrix is sorted in ascending order?

For example, consider the following matrix:

[1, 2, 3]
[-3, -5, 6]
[7, 8, 9]

When k=1 (first row), the row is sorted in ascending order. When k=2 (second row), the row is not sorted in ascending order.

Algorithm

The important point to note about matrices, is that a matrix is the stacking of one-dimensional arrays.

We can use the algorithm defined in this shot.

The steps of the algorithm are as follows:

  1. If the given row number, i.e.,k, is either greater than the number of rows or less than one (the first row), then there is no kth row in the given matrix.
  2. Start looping from the first element of the kth row.
  3. Compare every two elements.
    1. If the two elements are sorted, then move to the next element, i.e., i+1.
    2. Otherwise, it returns false, indicating the row is not sorted.
  4. The loop will eventually come to the end of the row when all the elements of the row are in sorted order.
  5. It will return true, indicating the kth row of the given matrix is sorted.

Implementation of the algorithm

Free Resources