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

Sorted matrix: 

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