A
A
Alexey2020-12-04 14:25:03
C++ / C#
Alexey, 2020-12-04 14:25:03

Sorting a two-dimensional array by the Bubble method, error, how to fix it?

Mistake

Run-Time Check Failure #2 - Stack around the variable 'mass' was corrupted.

The code itself is
#include <algorithm>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{ // mass[i][j]
  setlocale(LC_ALL, "rus");
  const int n = 4;
  const int m = 4;
  int mass[n][m] = { 16,15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
  srand(time(NULL));
  cout << "Случайно заполненный массив: " << endl;
  for (int i = 0; i < n; i++)
  {
    for (int j = 0; j < m; j++)
    {
      /*mass[i][j] = rand() % 20;*/
    }

  }

  for (int i = 0; i < n; i++)
  {
    for (int j = 0; j < m; j++)
    {
      cout << mass[i][j] << "\t";
    }
    cout << endl;
  }
  cout << "Сортировка методом Пузырька: " << endl;
  bool skip = false;
  while (!skip) {
    skip = true;
    for (int i = 0; i < n; i++)
    {
      for (int j = 0; j < m; j++)
      {
        if (mass[i][j] > mass[i][j + 1]) {
          swap(mass[i][j], mass[i][j + 1]);
          skip = false;
        }
        
      }
    }
  }


  for (int i = 0; i < n; i++)
  {
    for (int j = 0; j < m; j++)
    {
      cout << mass[i][j] << "\t";
    }
    cout << endl;
  }

}

Console output -5fca1c86af538342804173.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vreitech, 2020-12-04
@resolut1123

if (mass[i][j] > mass[i][j + 1]) {
          swap(mass[i][j], mass[i][j + 1]);

here you have an error: with j equal to m - 1, you crawl out of the array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question