Write the program described below.
Sample input/output
Sample Input :
Row=3
Column=4
Enter the array elements
1 2 3 4
9 8 7 6
4 5 6 7
Before sort:
1 2 3 4
9 8 7 6
4 5 6 7
After sort:
4 3 2 1
6 7 8 9
7 6 5 4Show answer
Answer
AIimport java.util.Scanner;
class Mix_sort
{
int a[][]; // stores the integer array
int m; // number of rows
int n; // number of columns
// parameterised constructor
Mix_sort(int row, int col)
{
m = row;
n = col;
a = new int[m][n];
}
// accepts the integer elements into a[][]
void input()
{
Scanner sc = new Scanner(System.in);
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
a[i][j] = sc.nextInt();
}
// arranges x[] in ascending order using insertion sort
void ascEven(int x[])
{
for (int i = 1; i < x.length; i++)
{
int key = x[i];
int j = i - 1;
while (j >= 0 && x[j] > key)
{
x[j + 1] = x[j];
j--;
}
x[j + 1] = key;
}
}
// arranges x[] in descending order using insertion sort
void dscOdd(int x[])
{
for (int i = 1; i < x.length; i++)
{
int key = x[i];
int j = i - 1;
while (j >= 0 && x[j] < key)
{
x[j + 1] = x[j];
j--;
}
x[j + 1] = key;
}
}
// sorts each row: even (1-indexed) row positions ascending, odd row positions descending
void arrange()
{
for (int i = 0; i < m; i++)
{
int row[] = new int[n];
for (int j = 0; j < n; j++)
row[j] = a[i][j];
if ((i + 1) % 2 == 0)
ascEven(row);
else
dscOdd(row);
for (int j = 0; j < n; j++)
a[i][j] = row[j];
}
}
// displays the original array, then arranges it and displays the sorted array
void display()
{
System.out.println("Before sort:");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
System.out.print(a[i][j] + "\t");
System.out.println();
}
arrange();
System.out.println("After sort:");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
System.out.print(a[i][j] + "\t");
System.out.println();
}
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Row=");
int row = sc.nextInt();
System.out.print("Column=");
int col = sc.nextInt();
Mix_sort obj = new Mix_sort(row, col);
System.out.println("Enter the array elements");
obj.input();
obj.display();
}
}Explanation: ascEven() and dscOdd() are both plain insertion sort, just with the comparison reversed. arrange() copies each row into a temporary array, sorts it ascending if the row's 1-indexed position is even and descending if odd, then writes it back into a[][]. display() prints the array as first entered, calls arrange(), then prints the result. Tested (run for real) with the question's own 3x4 example (rows 1 2 3 4 / 9 8 7 6 / 4 5 6 7): output was exactly 'Before sort: 1 2 3 4 / 9 8 7 6 / 4 5 6 7' then 'After sort: 4 3 2 1 / 6 7 8 9 / 7 6 5 4', matching the sample in the question.