Programming Basics SQL HTML CSS JavaScript Python C++ Java JavaFX Swing Problem Solving English English Conversations Computer Fundamentals Learn Typing

تحديات برمجيةالتحدي الخامس - حل التمرين الثالث بلغة جافا

المطلوب

أكتب برنامج يقوم بترتيب جميع القيم الموجودة في مصفوفة أرقام ثنائية جاهزة من الأصغر إلى الأكبر.
قم بعرض القيم الموجودة في المصفوفة قبل الترتيب و بعد الترتيب.


الحل بلغة جافا

public class Main {
public static void main(String[] args) {
int[][] matrix = {
{5, 2, 4},
{1, 7, 3},
{9, 8, 6}
};
int rows = matrix.length;
int cols = matrix[0].length;
int temp;
int[] array = new int[rows * cols];
System.out.println("Matrix before sorting");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
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 < array.length - 1; i++)
{
for (int j = i + 1; j < array.length; 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)];
}
}
System.out.println("\nMatrix after sorting");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
public class Main { public static void main(String[] args) { int[][] matrix = { {5, 2, 4}, {1, 7, 3}, {9, 8, 6} }; int rows = matrix.length; int cols = matrix[0].length; int temp; int[] array = new int[rows * cols]; System.out.println("Matrix before sorting"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } 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 < array.length - 1; i++) { for (int j = i + 1; j < array.length; 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)]; } } System.out.println("\nMatrix after sorting"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }

سنحصل على النتيجة التالية عند التشغيل.

Matrix before sorting 
5 2 4 
1 7 3 
9 8 6 

Matrix after sorting 
1 2 3 
4 5 6 
7 8 9