M
M
mpvcluuuuub2020-10-29 23:10:34
C++ / C#
mpvcluuuuub, 2020-10-29 23:10:34

What is wrong with matrix sorting?

According to the assignment, you need to create an algorithm that will sort a matrix from a two-dimensional array as follows: first there are negative numbers, then zeros, and then positive ones. It seems like I did it, but I don’t understand what my mistake is, if anything, then N is the number of rows and M is the number of columns

for (int i = 0; i < M; i++) {
    for (int j = 0; j < N; j++) {
      if (A[i][j] > 0) {
        for (int k = i + 1; k < N; k++) {
          for (int l = j + 1; l < M; l++) {
            if (A[k][l] < 0) {
              swap(A[k][l], A[i][j]);
            }
          }
        }
      }
    }
  }

  for (int i = M - 1; i >= 0; i--) {
    for (int j = N - 1; j >= 0; j--) {
      if (A[i][j] < 0) {
        for (int k = i; k >= 0; k--) {
          for (int l = j; l >= 0; l--) {
            if (A[k][l] > 0) {
              swap(A[k][l], A[i][j]);
            }
          }
        }
      }
    }
  }


5f9b22e3e0243031163634.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sumor, 2020-10-29
@Sumor

M and N are swapped

for (int k = i + 1; k < N; k++) {
          for (int l = j + 1; j < M; l++) {

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question