Display Boundary Elements & Sort Inner Matrix in Java

⚑ Direct Answer & Key Takeaway

Boundary elements of an `M x N` matrix occupy the outer frame where `i == 0`, `i == M - 1`, `j == 0`, or `j == N - 1`. Interior cells (`1 <= i <= M - 2` and `1 <= j <= N - 2`) form the inner matrix. Extract those `(M - 2) * (N - 2)` values into a 1D array, Bubble-sort it, and refill inner positions row-wise leaving boundary values intact.

1. Separating the Outer Frame from Non-Boundary Elements

Every `M x N` matrix with at least three rows and three columns splits cleanly into two disjoint zones. The outer ringβ€”top row (`i == 0`), bottom row (`i == M - 1`), left column (`j == 0`), and right column (`j == N - 1`)β€”contains `2 * (M + N) - 4` boundary elements. Subtracting `4` avoids counting the four corners twice. Meanwhile, the remaining `(M - 2) * (N - 2)` non-boundary cells never touch index `0` or the last index. Printing boundary elements requires replacing interior cells with blank tabs (`\t`) so the hollow rectangular frame aligns neatly.

  • Boundary check: `if (i == 0 || i == m - 1 || j == 0 || j == n - 1)`.
  • Inner check: `for (int i = 1; i < m - 1; i++) for (int j = 1; j < n - 1; j++)`.
  • Print `"\t"` (tab) in place of non-boundary elements when displaying the boundary frame.
  • A `2 x 2` or smaller matrix has zero inner elements (`(2 - 2) * (2 - 2) = 0`).

2. 3-Step Flatten, Bubble Sort, and Refill Workflow

Sorting a 2D interior block directly with 4-index swaps is error-prone during timed exams. Instead, flatten the inner cells into a 1D array `inner` of length `(m - 2) * (n - 2)` using index counter `k = 0`. Consider a `4 x 4` matrix whose inner `2 x 2` block holds `{ {9, 3}, {7, 1} }`. Extraction yields `inner = {9, 3, 7, 1}`. Bubble Sort rearranges `inner` to `{1, 3, 7, 9}`. Resetting `k = 0` and running the identical `1` to `m - 2` nested loop writes `{1, 3}` into row 1 and `{7, 9}` into row 2.

  • Step 1 (Extract): `inner[k++] = a[i][j];` inside `1 <= i <= m - 2` and `1 <= j <= n - 2`.
  • Step 2 (Sort): Standard ascending Bubble Sort on `inner` (`0` to `len - 1`).
  • Step 3 (Refill): Reset `k = 0`, then assign `a[i][j] = inner[k++];` over the same inner bounds.
  • Using `Arrays.sort()` is concise, but manual Bubble Sort demonstrates syllabus sorting mastery.

3. Exam Edge Cases: Minimum Dimensions & Hollow Alignment

CISCE board problems featuring boundary and non-boundary operations always enforce minimum size constraints such as `M > 2` and `N > 2` (commonly `3 <= M, N <= 10`), because smaller grids lack any interior sub-matrix. Validate `m < 3 || n < 3` right after scanning dimensions. When printing the hollow boundary view, remember to print a `\t` (tab) for skipped inner elements rather than omitting them completely; otherwise the right-hand boundary column collapses leftward next to the left-hand column and ruins the grid.

  • Reject dimensions `< 3` early so `new int[(m - 2) * (n - 2)]` never gets a negative or zero size.
  • Use `System.out.print("\t")` inside the `else` branch of the boundary display loop.
  • Check whether the question asks for ascending or descending sort before writing `<` vs `>` in Bubble Sort.

4. BoundaryAndInnerSort.java (ICSE BlueJ)

import java.util.*;

public class BoundaryAndInnerSort {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter rows and columns (both >= 3): ");
        int m = sc.nextInt();
        int n = sc.nextInt();

        if (m < 3 || n < 3) {
            System.out.println("Invalid size! Matrix must be at least 3x3.");
            sc.close();
            return;
        }

        int[][] a = new int[m][n];
        System.out.println("Enter " + (m * n) + " matrix elements:");
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                a[i][j] = sc.nextInt();
            }
        }

        System.out.println("\nOriginal Matrix:");
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(a[i][j] + "\t");
            }
            System.out.println();
        }

        System.out.println("\nBoundary Elements Only:");
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 || i == m - 1 || j == 0 || j == n - 1) {
                    System.out.print(a[i][j] + "\t");
                } else {
                    System.out.print("\t");
                }
            }
            System.out.println();
        }

        int innerSize = (m - 2) * (n - 2);
        int[] inner = new int[innerSize];
        int k = 0;
        for (int i = 1; i < m - 1; i++) {
            for (int j = 1; j < n - 1; j++) {
                inner[k++] = a[i][j];
            }
        }

        for (int i = 0; i < innerSize - 1; i++) {
            for (int j = 0; j < innerSize - 1 - i; j++) {
                if (inner[j] > inner[j + 1]) {
                    int temp = inner[j];
                    inner[j] = inner[j + 1];
                    inner[j + 1] = temp;
                }
            }
        }

        k = 0;
        for (int i = 1; i < m - 1; i++) {
            for (int j = 1; j < n - 1; j++) {
                a[i][j] = inner[k++];
            }
        }

        System.out.println("\nMatrix After Sorting Inner Elements:");
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(a[i][j] + "\t");
            }
            System.out.println();
        }
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter rows and columns (both >= 3): 4 4
Enter 16 matrix elements:
5 8 2 6 4 9 3 1 7 7 1 4 3 6 9 2

Original Matrix:
5	8	2	6	
4	9	3	1	
7	7	1	4	
3	6	9	2	

Boundary Elements Only:
5	8	2	6	
4			1	
7			4	
3	6	9	2	

Matrix After Sorting Inner Elements:
5	8	2	6	
4	1	3	1	
7	7	9	4	
3	6	9	2

5. CISCE Variable Description Table (VDT) & Dry Run

VariableData TypeExam Purpose & Sample Value
scScannerReads matrix dimensions and integer elements
m, nintRow and column counts, validated >= 3 (sample: m = 4, n = 4)
a[][]int[][]4x4 matrix updated in-place for inner elements
inner[]int[]1D array holding (m-2)*(n-2) interior values ({9, 3, 7, 1} -> {1, 3, 7, 9})
kintIndex pointer used during inner extraction and refill (0..3)
tempintTemporary swap variable inside Bubble Sort
🎯 1-on-1 Live Mentorship & Free Study Kit

Master Tough ICSE Boundary & Sorting Matrix Problems

Walk through 2D flattening, Bubble Sort dry runs, and hollow-grid formatting with a dedicated 1-on-1 Java tutor.

πŸ’¬ WhatsApp Now
πŸ”’ Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Using `&&` instead of `||` in the boundary condition (`i == 0 && i == m - 1 ...`), which never evaluates to `true` and prints an empty grid.
  • Avoid Mistake: Forgetting to print a blank `\t` in the `else` branch of the boundary display loop, shifting the right column inward and breaking visual alignment.
  • Avoid Mistake: Writing `k` without resetting `k = 0` before refilling the sorted `inner[]` elements back into `a[i][j]`, throwing `ArrayIndexOutOfBoundsException`.
  • Examiner / Mentor Tip: Explain why Bubble Sort on a flattened 1D array is preferred over 2D index conversion (`inner[idx / cols][idx % cols]`)β€”it minimizes off-by-one bugs under exam pressure.
  • Examiner / Mentor Tip: If the question also asks for the sum of boundary elements, add `sum += a[i][j]` right inside the boundary `if` block so you don't need a separate loop.
  • Examiner / Mentor Tip: Remember that a `3 x 3` matrix has only `1` inner element (`a[1][1]`), so always test your code on `4 x 4` or `4 x 5` when checking sorting.

7. Interactive Concept Check Quiz

Question: How many non-boundary (inner) elements exist in a `5 x 4` integer matrix?

8. Frequently Asked Questions

How do you calculate the exact count of boundary elements in an M x N matrix?
An `M x N` matrix (`M, N >= 2`) has `(M - 2) * (N - 2)` inner elements, so the boundary contains `M * N - (M - 2) * (N - 2)` elements, which simplifies cleanly to `2 * M + 2 * N - 4`. Subtracting `4` removes the four corner cells counted twice.
Can I use Arrays.sort(inner) instead of Bubble Sort in the ICSE board exam?
While `Arrays.sort(inner)` compiles cleanly with `import java.util.*;`, ICSE board questions that ask you to sort elements usually expect a manual Bubble Sort or Selection Sort implementation. Writing the explicit nested comparison and swap loop demonstrates core algorithmic knowledge and prevents losing marks under strict CISCE rubrics.
Why must the matrix be at least 3x3 for sorting inner elements?
Every element in a `1 x N`, `M x 1`, or `2 x 2` matrix sits on at least one outer edge (`i == 0`, `i == M - 1`, `j == 0`, or `j == N - 1`). Because there are zero interior cells to extract or sort, `M >= 3` and `N >= 3` is required.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class