Program opened below. You can scroll through the algorithm, Java code and output.
Program 20
Merge Both Diagonals in Ascending Order
Question
Read an n×n matrix and merge the two diagonals into one sorted array. Include the centre element only once when n is odd.
Algorithm
Step 1: Start and read the order n.
Step 2: Reject a nonpositive or excessive order.
Step 3: Create the square matrix.
Step 4: Input its values.
Step 5: Calculate the space required for two diagonals.
Step 6: Subtract one when their centre position overlaps.
Step 7: Create the one-dimensional merged array.
Step 8: Set the insertion pointer to zero.
Step 9: Move down the principal diagonal.
Step 10: Copy each principal-diagonal value to the result.
Step 11: Also copy the secondary-diagonal value from the same row when the indices differ.
Step 12: Continue until every row is examined.
Step 13: Sort the merged array using insertion sort.
Step 14: Display each value in sorted order.
Step 15: Stop.
Java program
Javaimport java.util.*;
class DiagonalMerge {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n < 1 || n > 20) {
System.out.println("Invalid order");
return;
}
int[][] a = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = sc.nextInt();
}
}
int size = n * 2;
if (n % 2 == 1) {
size--;
}
int[] merged = new int[size];
int pos = 0;
for (int i = 0; i < n; i++) {
merged[pos++] = a[i][i];
if (i != n - 1 - i) {
merged[pos++] = a[i][n - 1 - i];
}
}
for (int i = 1; i < size; i++) {
int key = merged[i];
int j = i - 1;
while (j >= 0 && merged[j] > key) {
merged[j + 1] = merged[j];
j--;
}
merged[j + 1] = key;
}
for (int x : merged) {
System.out.print(x + " ");
}
}
}Sample output
Input: 2 / 1 2 / 3 4
Output: 1 2 3 4