Advertisement
Guest User

Untitled

a guest
Jun 21st, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. // Test C++.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4.  
  5.  
  6.  
  7. #include "stdafx.h"
  8. #include <vector>
  9. #include <iostream>
  10.  
  11. using namespace std;
  12.  
  13. // !!!
  14. // Write function Sort, that will sort the rows of matrix in ascending order.
  15. // Sorting must be done in-place.
  16. void SortMatrix(vector<vector<int>> & matrix)
  17. {
  18. int rows = matrix.size();
  19. int cols = matrix[0].size();
  20.  
  21. size_t size = rows * cols;
  22. int* ar = new int[size];
  23.  
  24. int count = 0;
  25. for (int i = 0; i < rows; i++)
  26. {
  27. for (int j = 0; j < cols; j++)
  28. {
  29. int index = i * cols + j;
  30. ar[i * cols + j] = matrix[i][j];
  31. count++;
  32. }
  33. }
  34.  
  35. //sort
  36. for (size_t i = 0; i < size; i++)
  37. {
  38. for (size_t j = 0; j < size - i - 1; j++)
  39. {
  40. if (ar[j] > ar[j + 1])
  41. std::swap(ar[j], ar[j + 1]);
  42. }
  43. }
  44.  
  45. for (int i = 0; i < rows; i++)
  46. {
  47. for (int j = 0; j < cols; j++)
  48. {
  49. int index = i * cols + j;
  50. matrix[i][j] = ar[i * cols + j];
  51. count++;
  52. }
  53. }
  54.  
  55. cout << endl;
  56. delete[] ar;
  57. }
  58.  
  59. void PrintMatrix(vector<vector<int>> & matrix)
  60. {
  61. for (auto & row : matrix) {
  62. for (auto & cell : row) {
  63. cout << cell << "\t";
  64. }
  65. cout << endl;
  66. }
  67. cout << endl;
  68. }
  69.  
  70. void Sort()
  71. {
  72. int ar[10] = {6, 8, 4, 3, 9, 7, 0, 1, 2, 5};
  73. size_t size = 10;
  74.  
  75. for (size_t i = 0; i < size; i++)
  76. {
  77. for (size_t j = 0; j < size - i - 1; j++)
  78. {
  79. if(ar[j] > ar[j + 1])
  80. std::swap(ar[j], ar[j + 1]);
  81. }
  82. }
  83.  
  84. for (size_t i = 0; i < size; i++)
  85. cout << ar[i] << ' ';
  86.  
  87. cout << endl;
  88.  
  89. }
  90.  
  91. int main()
  92. {
  93. vector<vector<int>> m1 =
  94. {
  95. { 9, 8 },
  96. { 1, 12 },
  97. { 3, 5 },
  98. };
  99.  
  100. vector<vector<int>> m2 =
  101. {
  102. { 9, 8, 6 },
  103. { 4, 12, 2 },
  104. { 3, 5, 11 },
  105. };
  106.  
  107. SortMatrix(m1);
  108. PrintMatrix(m1);
  109.  
  110. SortMatrix(m2);
  111. PrintMatrix(m2);
  112.  
  113. return 0;
  114. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement