How to sort a two-dimensional array using .sort ()?
  • one
    How to use "in general" or how to sort a two-dimensional array? - KoVadim
  • and so and so) - Not even close
  • 2
    And how do you imagine a sorted two-dimensional array? - delphist007
  • And what does sorting a two-dimensional array mean? - avp
  • one
    There is a possibility that the vehicle wants to sort each array in an array ... - Salivan

3 answers 3

If you have an int ** native array, then it can be sorted as one-dimensional.

int arr[10][10]; //какая-то инициализация std::sort(arr,arr + 10*10,std::greater<int>()); 

Something like this

  • The author, of course, did not say by what criteria he wants to sort the matrix, but in your case any connection between the elements and the rows / columns of the original array is simply lost. - avp
  • Any task of sorting a 2d array, taking into account its dimension, is always reduced to sorting a set of 1d arrays. If this rule is not met, then it is usually worth thinking about changing the design. - Andrey Buran
  • But usually reorder the rows or columns, and do not mix the contents of the matrix. - avp
  • Usually a strange word in this context - Andrey Buran
 bool compare(int* x, int* y) { return ( (x[0] < y[0]) || ((x[0] == y[0]) && (x[1] < y[1])) ); } 

-

 // Двумерный массив int** array = ... // Количество строк int rows = ... // Сортировка массива std::sort(array, array + rows, &compare); 
  • will not take off. you sort the items from first to first plus the number of rows in the array. - Andrey Buran

If you need, then that in the figure below, and also, the sorting algorithm (technology) itself is needed, then deal with my code.

alt text

The bubble sort code is one of the simplest and most imperfect:

 #include <iostream> #include <iomanip> #include <time.h> using namespace std; int main() { srand(time(0)); int a[20][20]; int b[20][20]; unsigned short n, m, i, j, k; do { cout << "2 <= N <= 2; 2 <= M <= 2" << endl; cout << "N = "; cin >> n; cout << "M = "; cin >> m; } while (((n < 2) || (n > 20)) || ((m < 2) || (m > 20))); cout << endl << "Ishodnaya matricza:" << endl << endl; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { a[i][j] = (rand() % 100) - 50; b[i][j] = a[i][j]; cout << setw(4) << a[i][j]; } cout << endl; } int tmp; // переменная для временного хранения числа cout << endl << "Sortirovka po strokam:" << endl << endl; for (i = 0; i < n; i++) // мотаю цикл строк for (j = 0; j < m-1; j++) // мотаю цикл столбцов for (k = j; k < m; k++) // сортирующий цикл if (a[i][j] > a[i][k]) // условие на сортировку { // для сортировки по убыванию достаточно заменить ">" на "<" tmp = a[i][j]; // сохраняю максимум из 2-ух чисел в переменную a[i][j] = a[i][k]; // минимум из этих чисел "всплывает" вверх a[i][k] = tmp; // максимум отправляю вниз (на место минимума) } for (i = 0; i < n; i++) { for (j = 0; j < m; j++) cout << setw(4) << a[i][j]; cout << endl; } cout << endl << "Sortirovka po stolbczam:" << endl << endl; for (j = 0; j < m; j++) for (i = 0; i < n-1; i++) for (k = i; k < n; k++) if (b[i][j] > b[k][j]) { tmp = b[i][j]; b[i][j] = b[k][j]; b[k][j] = tmp; } for (i = 0; i < n; i++) { for (j = 0; j < m; j++) cout << setw(4) << b[i][j]; cout << endl; } cout << endl << "Davi na ENTER!!!"; cin.get(); cin.get(); return 0; } 

As I explained above, the bubble method is a very inefficient, more advanced algorithm below (option for sorting by rows):

 cout << endl << "Sortirovka po strokam:" << endl << endl; int tmp; // временная переменная unsigned short minind, // индекс минимального элемента mm = m - 1; // для цикла прокрутки столбцов for (i = 0; i < n; i++) // мотаю цикл строк { for (j = 0; j < mm; j++) // мотаю цикл столбцов { minind = j; // предполагаемый индекс минимума for (k = j+1; k < m; k++) // сортирующий цикл if (a[i][minind] > a[i][k]) // условие для поиска индекса минимума minind = k; // меняю местами минимум с j-тым элементом tmp = a[i][j]; a[i][j] = a[i][minind]; a[i][minind] = tmp; } } 

This code can be optimized if the number of passes of the column scrolling cycle is reduced by 2 times - if both the minimum and maximum are searched for in the sorting cycle, and in this cycle, the minimum is sent to the beginning of the row (or column), and the maximum to the end. There are a lot of algorithms for sorting arrays, but as far as I know, the most optimal algorithms justify themselves only when sorting large arrays.

ZY Code compiled in Dev-C ++ Compiler.

  • one
    It seems that the question was about sort ... - mega