SUNDAY, 12 JULY 2026
Guide For School logo Guide For SchoolStudy Guide For Students On Java Programming
Physics | Chemistry | Mathematics
ICSE | ISC | CBSE
Guide For School logo Guide For SchoolICSE and ISC Resources

2D Array Sorting Program in Java and Python

08 November 2013

2D Array sorting program with algorithm, explanation, Java methods and a simple Python solution for ICSE and ISC students.

Question:

Write a program to input a two-dimensional array and sort all its elements in ascending order. The sorted values should again be displayed in matrix form. One clear method is to copy the matrix elements into a 1-D array, sort that array, and then refill the matrix.

INPUT: Enter the number of rows: 2 Enter the number of columns: 3 Enter the elements: 9 4 7 1 6 3 OUTPUT: The original array: 9 4 7 1 6 3 The sorted array: 1 3 4 6 7 9

Algorithm:

Step 1: Start.

Step 2: Accept rows m and columns n.

Step 3: Declare matrix A[m][n] and input all values using nested loops.

Step 4: Display A in row-column form.

Step 5: Declare one-dimensional array B of size m × n and initialize index x to 0.

Step 6: Using nested loops, copy A[i][j] into B[x] and increment x after each copy.

Step 7: Sort B in ascending order by comparing B[i] with B[j] for all later positions and swapping when B[i] is greater.

Step 8: Reset x to 0.

Step 9: Using nested loops, copy B[x] back into A[i][j] and increment x after each copy.

Step 10: Display the sorted matrix A.

Step 11: Stop.

Explanation:

The program sorts a two-dimensional array by temporarily converting it into a one-dimensional array. This method is simple to trace because sorting a single list is easier than directly comparing elements across rows and columns. First, the program accepts the number of rows and columns, then stores all input values in matrix A using nested loops. The same nested-loop structure is used to display the original matrix in row-column form.

The important step is copying the matrix into array B. The variable x acts as the current position in B. Each element A[i][j] is copied into B[x], and x is increased after every copy. This preserves all elements of the matrix while changing only the storage form from two-dimensional to one-dimensional.

After copying, the program sorts B in ascending order using comparison and swapping. For every position i, the later positions are checked. If a smaller element is found later, the two values are exchanged using temporary variable t. Once B is sorted, the program copies its values back into matrix A using nested loops again. This fills the matrix row by row with sorted values, giving a sorted two-dimensional array without needing a complex direct matrix-sorting technique.

Java Program Using 1-D Array:

Java
/**
* The class Sort2D_Method1 inputs a two dimensional array and sorts it in ascending order
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
*/

import java.util.Scanner;
class Sort2D_Method1
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the no. of  rows: "); //inputting number of rows
        int m=sc.nextInt();
        System.out.print("Enter the no. of columns: "); //inputting number of columns
        int n=sc.nextInt();

        int A[][]=new int[m][n]; //creating a 2D array

        /* Inputting the 2D Array */

        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                System.out.print("Enter the elements: ");
                A[i][j]=sc.nextInt();
            }
        }

        /* Printing the original 2D Array */

        System.out.println("The original array:");
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                System.out.print(A[i][j]+"\t");
            }
            System.out.println();
        }

        /* Saving the 2D Array into a 1D Array */

        int B[]=new int[m*n]; //creating a 1D Array of size 'r*c'
        int x = 0;
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                B[x] = A[i][j];
                x++;
            }
        }

        /*Sorting the 1D Array in Ascending Order*/

        int t=0;
        for(int i=0; i<(m*n)-1; i++)
        {
            for(int j=i+1; j<(m*n); j++)
            {
                if(B[i]>B[j])
                {
                    t=B[i];
                    B[i]=B[j];
                    B[j]=t;
                }
            }
        }

        /*Saving the sorted 1D Array back into the 2D Array */

        x = 0;
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                A[i][j] = B[x];
                x++;
            }
        }

        /* Printing the sorted 2D Array */

        System.out.println("The Sorted Array:");
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                System.out.print(A[i][j]+"\t");
            }
            System.out.println();
        }
    }
}

Java Program Using Direct Sorting:

Java
/**
* The class Sort2D_Method2 inputs a two dimensional array and sorts it in ascending order
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
*/

import java.util.Scanner;
class Sort2D_Method2
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the no. of  rows: "); //inputting number of rows
        int m=sc.nextInt();
        System.out.print("Enter the no. of columns: "); //inputting number of columns
        int n=sc.nextInt();

        int A[][]=new int[m][n]; //creating a 2D array

        /* Inputting the 2D Array */

        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                System.out.print("Enter the elements: ");
                A[i][j]=sc.nextInt();
            }
        }

        /* Printing the original 2D Array */

        System.out.println("The original array:");
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                System.out.print(A[i][j]+"\t");
            }
            System.out.println();
        }

        /* Sorting the 2D Array */

        int t=0;
        for(int x=0;x<m;x++)
        {
            for(int y=0;y<n;y++)
            {
                for(int i=0;i<m;i++)
                {
                    for(int j=0;j<n;j++)
                    {
                        if(A[i][j]>A[x][y])
                        {
                            t=A[x][y];
                            A[x][y]=A[i][j];
                            A[i][j]=t;
                        }
                    }
                }
            }
        }

        /* Printing the sorted 2D Array */

        System.out.println("The Sorted Array:");
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                System.out.print(A[i][j]+"\t");
            }
            System.out.println();
        }
    }
}

Equivalent Python Program:

Python
# Read the matrix or array size and store the values for indexed processing.
# Nested loops are used because each row/column or array position must be checked.
# Print the processed array or matrix in the required output format.

m = int(input("Enter the number of rows: "))
n = int(input("Enter the number of columns: "))

A = []
print("Enter the elements:")
for i in range(m):
    row = []
    for j in range(n):
        row.append(int(input()))
    A.append(row)

print("The original array:")
for i in range(m):
    for j in range(n):
        print(A[i][j], end="	")
    print()

B = []
for i in range(m):
    for j in range(n):
        B.append(A[i][j])

for i in range(len(B) - 1):
    for j in range(i + 1, len(B)):
        if B[i] > B[j]:
            t = B[i]
            B[i] = B[j]
            B[j] = t

x = 0
for i in range(m):
    for j in range(n):
        A[i][j] = B[x]
        x = x + 1

print("The sorted array:")
for i in range(m):
    for j in range(n):
        print(A[i][j], end="	")
    print()

Output:

INPUT: Enter the number of rows: 2 Enter the number of columns: 3 Enter the elements: 9 4 7 1 6 3 OUTPUT: The original array: 9 4 7 1 6 3 The sorted array: 1 3 4 6 7 9

Leave a Reply

Your email address will not be published. Comments are reviewed before appearing publicly.

Send a comment or correction

Study smarter

Everything you need for ICSE and ISC Computer

Programs, revision notes, solved papers and practical guidance—organized for quick study.

Browse all resources →