تحديات برمجيةالتحدي الخامس - حل التمرين الثالث بلغة C++
المطلوب
أكتب برنامج يقوم بترتيب جميع القيم الموجودة في مصفوفة أرقام ثنائية جاهزة من الأصغر إلى الأكبر.
قم بعرض القيم الموجودة في المصفوفة قبل الترتيب و بعد الترتيب.
الحل بلغة C++
#include <iostream>
int main() {
int matrix[3][3] = {
{ 5, 2, 4 },
{ 1, 7, 3 },
{ 9, 8, 6 }
};
int rows = sizeof(matrix) / sizeof(matrix[0]);
int cols = sizeof(matrix[0]) / sizeof(int);
int temp;
int array[rows * cols];
std::cout << "Matrix before sorting\n";
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
std::cout << matrix[i][j] << " ";
}
std::cout << "\n";
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
array[j + (i * rows)] = matrix[i][j];
}
}
for (int i = 0; i < (rows * cols) - 1; i++)
{
for (int j = i + 1; j < rows * cols; j++)
{
if (array[j] < array[i])
{
temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
matrix[i][j] = array[j + (i * rows)];
}
}
std::cout << "\nMatrix after sorting\n";
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
std::cout << matrix[i][j] << " ";
}
std::cout << "\n";
}
char end; std::cin >> end;
return 0;
}
#include <iostream>
int main() {
int matrix[3][3] = {
{ 5, 2, 4 },
{ 1, 7, 3 },
{ 9, 8, 6 }
};
int rows = sizeof(matrix) / sizeof(matrix[0]);
int cols = sizeof(matrix[0]) / sizeof(int);
int temp;
int array[rows * cols];
std::cout << "Matrix before sorting\n";
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
std::cout << matrix[i][j] << " ";
}
std::cout << "\n";
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
array[j + (i * rows)] = matrix[i][j];
}
}
for (int i = 0; i < (rows * cols) - 1; i++)
{
for (int j = i + 1; j < rows * cols; j++)
{
if (array[j] < array[i])
{
temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
matrix[i][j] = array[j + (i * rows)];
}
}
std::cout << "\nMatrix after sorting\n";
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
std::cout << matrix[i][j] << " ";
}
std::cout << "\n";
}
char end; std::cin >> end;
return 0;
}
سنحصل على النتيجة التالية عند التشغيل.
Matrix before sorting 5 2 4 1 7 3 9 8 6 Matrix after sorting 1 2 3 4 5 6 7 8 9