The error on sorting is fixed by replacing the word "rows", with the word "cols", in the sorting part of the code, at the bottom.
Go below the sort of the row_sums, to the part where the matrix elements for the row
are being swapped.
just remove the word "rows", there, and put in the word "cols".
for(k = 0; k < rows; k++)
should be:
for(k = 0; k < cols; k++)
That fixes it.