M
M
mpvcluuuuub2020-10-23 17:48:41
C++ / C#
mpvcluuuuub, 2020-10-23 17:48:41

How to sort a matrix?

I need to sort the matrix created using a two-dimensional dynamic array so that negative numbers go first, without creating an additional matrix, M is the number of columns N is the number of rows, the code is given below, it turns out that negative numbers simply remain in the right side of the matrix, I don't understand what the problem is5f92ed3099a6a346527538.png

#include <iostream>
#include <ctime>
#include <iomanip> /*iomanip тут просто чтобы красиво было*/

using namespace std;

void main() {
  setlocale(LC_ALL, "Russian");
  srand(time(NULL));

  cout << "Введите количество строк в матрице А: ";
  int N;
  cin >> N;
  cout << "Введите количество столбцов в матрице А: ";
  int M;
  cin >> M;

  int** A = new int* [N];

  for (int i = 0; i < N; i++) {
    A[i] = new int[M];
  }

  for (int i = 0; i < N; i++) {
    for (int j = 0; j < M; j++) {
      A[i][j] = rand() % 21 - 10;
    }
  }

  cout << "Созданная матрица A" << endl;

  for (int i = 0; i < N; i++) {
    for (int j = 0; j < M; j++) {
      cout << setw(3) << A[i][j] << " ";
    }
    cout << endl;
  }

  cout << endl;

  for (int i = 0; i < N; i++) {
    for (int j = 0; j < M; j++) {
      int minusI = i;
      int minusJ = j;
      for (int currentElement = 0; currentElement < M; currentElement++) {
        if (A[i][currentElement] < 0) {
          int temp;
          temp = A[i][currentElement];
          A[i][currentElement] = A[minusI][minusJ];
          A[minusI][minusJ] = temp;
        }
      }
    }
  }

  cout << "Матрица в отсортированном виде: " << endl;

  for (int i = 0; i < N; i++) {
    for (int j = 0; j < M; j++) {
      cout << setw(3) << A[i][j] << " ";
    }
    cout << endl;
  }

  for (int i = 0; i < N; i++) {
    delete[] A[i];
  }

  delete[] A;
  system("pause");
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-10-23
@jcmvbkbc

I do not understand what the problem is

and you explain how your algorithm works and why there are two nested loops on the columns - and maybe you will understand.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question