Program opened below. You can scroll through the algorithm, Java code and output.

Arrange Each Row of a Matrix in Ascending Order

Download .java

Question

Arrange the elements of each row of a square two-dimensional array in ascending order using bubble sort.

Step 1: Start the program and create a Scanner object for keyboard input. Step 2: Accept the order n of the square matrix and check that n is positive. Step 3: Declare a two-dimensional integer array of n rows and n columns. Step 4: Read all matrix elements using an outer loop for rows and an inner loop for columns. Step 5: Select the first row and begin a bubble-sort pass over its adjacent elements. Step 6: Compare each element with the element immediately to its right. Step 7: If the left element is greater, interchange the two elements using a temporary variable. Step 8: Continue the pass to the end of the unsorted portion of the row. Step 9: Repeat the passes until the row is arranged in ascending order. Step 10: Move to the next row and repeat the same sorting procedure. Step 11: Continue until every row has been sorted independently. Step 12: Display the resulting matrix row by row, placing each row on a separate line. Step 13: Stop the program.
Java
import java.util.*;
class RowBubbleSort
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter order: ");
        int n = sc.nextInt();
        int[][] a = new int[n][n];
        System.out.println("Enter matrix elements:");
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                a[i][j] = sc.nextInt();
            }
        }
        for (int i = 0; i < n; i++)
        {
            for (int pass = 0; pass < n - 1; pass++)
            {
                for (int j = 0; j < n - pass - 1; j++)
                {
                    if (a[i][j] > a[i][j + 1])
                    {
                        int t = a[i][j];
                        a[i][j] = a[i][j + 1];
                        a[i][j + 1] = t;
                    }
                }
            }
        }
        System.out.println("Sorted matrix:");
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                System.out.print(a[i][j] + "\t");
            }
            System.out.println();
        }
    }
}
Input: Input: 2; matrix: 4 1 / 3 2 Output: Sorted matrix: 1 4 2 3
← Previous Program 31 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.