fork download
  1. #include <cmath>
  2. #include <ctime>
  3. #include <iostream>
  4.  
  5. int** CreateMatrix(int x, int y)
  6. {
  7. int** matrix = new int *[x];
  8. for (int row = 0; row < x; ++row)
  9. matrix[row] = new int[y];
  10. return matrix;
  11. }
  12.  
  13. void FillMatrix(int** mtx, int x, int y)
  14. {
  15. srand(time(nullptr));
  16. for (int row = 0; row < x; ++row)
  17. {
  18. for (int col = 0; col < y; ++col)
  19. {
  20. mtx[row][col] = 1 + rand() % 9;
  21. }
  22. }
  23. }
  24.  
  25. void PrintMatrix(int** mtx, int x, int y)
  26. {
  27. for (int row = 0; row < x; ++row)
  28. {
  29. for (int col = 0; col < y; ++col)
  30. {
  31. std::cout << mtx[row][col] << " ";
  32. }
  33. std::cout << std::endl;
  34. }
  35. }
  36.  
  37. void SortVector(int** vector, int y, int size)
  38. {
  39. int i = 0;
  40. int buf;
  41. char swap_cnt = 0;
  42. while (i < size)
  43. {
  44. if (i + 1 != size && vector[i][y] > vector[i + 1][y])
  45. {
  46. buf = vector[i][y];
  47. vector[i][y] = vector[i + 1][y];
  48. vector[i + 1][y] = buf;
  49. swap_cnt = 1;
  50. }
  51. i++;
  52. if (i == size && swap_cnt == 1)
  53. {
  54. swap_cnt = 0;
  55. i = 0;
  56. }
  57. }
  58. }
  59.  
  60. void SortColsMatrix(int** mtx, int x, int y)
  61. {
  62. for (int col = 0; col < y; ++col)
  63. {
  64. SortVector(mtx, col, x);
  65. }
  66. }
  67.  
  68. void FreeMatrix(int** &mtx, int x, int y)
  69. {
  70. for (int row = 0; row < x; ++row)
  71. delete[] mtx[row];
  72. delete[] mtx;
  73. }
  74.  
  75. int main()
  76. {
  77. int x = 7;
  78. int y = 5;
  79. int** mtx = CreateMatrix(x,y);
  80. FillMatrix(mtx, x, y);
  81.  
  82. std::cout << "Unsorted matrix: " << std::endl;
  83. PrintMatrix(mtx, x, y);
  84. std::cout << std::endl;
  85.  
  86. SortColsMatrix(mtx, x, y);
  87.  
  88. std::cout << "Sorted matrix: "<< std::endl;
  89. std::cout << std::endl;
  90. PrintMatrix(mtx, x, y);
  91.  
  92. FreeMatrix(mtx, x, y);
  93.  
  94. return 0;
  95. }
Success #stdin #stdout 0s 4376KB
stdin
Standard input is empty
stdout
Unsorted matrix: 
3 3 6 3 7 
9 4 8 5 5 
4 4 3 3 8 
1 2 1 6 1 
5 5 8 9 9 
6 3 8 6 2 
6 6 2 2 9 

Sorted matrix: 

1 2 1 2 1 
3 3 2 3 2 
4 3 3 3 5 
5 4 6 5 7 
6 4 8 6 8 
6 5 8 6 9 
9 6 8 9 9