## Friday, November 11, 2016

### Count all sorted rows in a matrix - GeeksforGeeks

Count all sorted rows in a matrix - GeeksforGeeks
Given a matrix of m*n size, the task is to count all the rows in a matrix that are sorted either in strictly increasing order or in strictly decreasing order?

1) Traverse from left side of the matrix to count all the row which are in strictly increasing order
2) Traverse from right side of the matrix to count all the row which are in strictly decreasing order
We can traverse it just once.
`int` `sortedCount(``int` `mat[][MAX], ``int` `r, ``int` `c)`
`{`
`    ``int` `result = 0; ``// Initialize result`

`    ``// Start from left side of matrix to`
`    ``// count increasing order rows`
`    ``for` `(``int` `i=0; i<r; i++)`
`    ``{`
`        ``// Check if there is any pair ofs element`
`        ``// that are  not in increasing order.`
`        ``int` `j;`
`        ``for` `(j=0; j<c-1; j++)`
`            ``if` `(mat[i][j+1] <= mat[i][j])`
`                ``break``;`

`        ``// If the loop didn't break (All elements`
`        ``// of current row were in increasing order)`
`        ``if` `(j == c-1)`
`            ``result++;`
`    ``}`

`    ``// Start from right side of matrix to`
`    ``// count increasing order rows ( refrence`
`    ``// to left these are in decreasing order )`
`    ``for` `(``int` `i=0; i<r; i++)`
`    ``{`
`        ``// Check if there is any pair ofs element`
`        ``// that are  not in decreasing order.`
`        ``int` `j;`
`        ``for` `(j=c-1; j>0; j--)`
`            ``if` `(mat[i][j-1] <= mat[i][j])`
`                ``break``;`

`        ``// Note c > 1 condition is required to make`
`        ``// sure that a single column row is not counted`
`        ``// twice (Note that a single column row is sorted`
`        ``// both in increasing and decreasing order) `
`        ``if` `(c > 1 && j == 0)`
`            ``result++;`
`    ``}`
`    ``return` `result;`
`}`