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

Sort Alternate Matrix Rows

Download .java

Question

Input a matrix with 3 to 10 rows and up to 7 columns; sort odd-numbered rows ascending and even-numbered rows descending.

Step 1: Start and create Scanner. Step 2: Read the number of rows. Step 3: Read the number of columns. Step 4: Validate both dimensions. Step 5: Create the required integer matrix. Step 6: Read the matrix values row by row. Step 7: Begin processing the first row. Step 8: Decide the direction from the row index parity. Step 9: Use ascending order for the first, third and other odd-numbered rows. Step 10: Use descending order for the second, fourth and other even-numbered rows. Step 11: Apply insertion sort to the current row. Step 12: Select the next value and store it as key. Step 13: Shift earlier values that violate the required direction. Step 14: Insert the key into its sorted position. Step 15: Repeat for every row. Step 16: Display the resulting matrix and stop.
Java
import java.util.*;
class AlternateRows {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int n = sc.nextInt();
        if (m < 3 || m > 10 || n < 1 || n > 7) {
            System.out.println("Invalid order");
            return;
        }
        int[][] a = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                a[i][j] = sc.nextInt();
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 1; j < n; j++) {
                int key = a[i][j];
                int k = j - 1;
                while (k >= 0 && ((i % 2 == 0 && a[i][k] > key) || (i % 2 == 1 && a[i][k] < key))) {
                    a[i][k + 1] = a[i][k];
                    k--;
                }
                a[i][k + 1] = key;
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Input: 3 3 / 3 1 2 / 4 6 5 / 9 7 8 Output: 1 2 3 / 6 5 4 / 7 8 9
← Previous Program 18 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.