M
M
Mag1str2021-06-20 14:24:24
C++ / C#
Mag1str, 2021-06-20 14:24:24

Have I sorted the matrix correctly?

Task:
Given a square two-dimensional array (matrix) of integers А[n, n]. Sort the side diagonal of the array using insertion method #1 (with linear search on the left) in ascending order.

Decision:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    srand((int)time(0));
    int N, n;
    cout << "N=";
    cin >> n;


    int **a= new int *[n];
    for (int i = 0; i < n; i++)
        a[i] = new int[n];

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            a[i][j]=rand()%9 + 1;
            cout << a[i][j] << " ";
        }
        cout << "\n";
    }
    cout << "\n";

    for (int i = 0; i < n-1; i++)
        for (int j = 0; j < n-i-1; j++)
            if (a[j][j] > a[j+1][j+1])
                swap(a[j][j], a[j+1][j+1]);

    for (int i = 0; i < n-1; i++)
        for (int j = 0; j < n-i-1; j++)
            if (a[n-1-j][j] > a[n-2-j][j+1])
                swap(a[n-1-j][j], a[n-2-j][j+1]);

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
            cout << a[i][j] << " ";
        cout << "\n";
    }

    for (int i = 0; i < n; i++)
        delete[]a[i];
    delete[]a;
    system("pause");
    return 0;
}


Result:
60cf25663224e004054953.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Petryaev, 2021-06-23
@Gremlin92

Not correct and the insert method is somehow not visible

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question