Computer Science, asked by tanyaibanez23, 5 months ago

Write a program to create a 5 x 6 numeric array. Input choice from the user asking whether sorting is to be
done rowwise or columnwise an print the output​

Answers

Answered by anindyaadhikari13
1

Question:-

Write a program to create a 5 x 6 numeric array. Input choice from the user asking whether sorting is to be done row-wise or column-wise an print the output.

Program:-

This is a good question. Check out the answer here.

I am using selection sort algorithm to sort the 2D array row-wise of column-wise as per the user requirement (in ascending order).

import java.util.*;

class Array

{

public static void main(String s[])

{

Scanner sc=new Scanner(System.in);

int r=5, c=6;

int a[][]=new int[r][c];

System.out.println("Enter the numbers in 5x6 2D array...");

for(int i=0;i<r;i++)

{

for(int j=0;j<c;j++)

{

System.out.print("["+i+"]["+j+"] = ");

a[i][j]=sc.nextInt();

}

System.out.println();

}

System.out.println("Enter 1 for sorting row-wise and 2 for sorting column-wise. ");

int ch=sc.nextInt();

switch(ch)

{

case 1:

// sorting row-wise

for(int i=0;i<r;i++)

{

for(int j=0;j<c;j++)

{

for(int k=j+1;k<c;k++)

{

if(a[i][j]>a[i][k])

{

int t=a[i][j];

a[i][j]=[i][k];

a[i][k]=t;

}// end of if.

}// end of third loop

}// end of second loop.

}// end of first loop.

break;

case 2:

// sorting column-wise

for(int i=0;i<c;i++)

{

for(int j=0;j<r;j++)

{

for(int k=j+1;k<r;k++)

{

if(a[j][i]>a[k][i])

{

int t=a[j][i];

a[j][i]=a[k][i];

a[k][i]=t;

}// end of if.

}// end of third loop

}// end of second loop.

}// end of first loop.

break;

default:

System.out.println("Invalid choice. ");

System.exit(0);

}

System.out.println("Given 2D array after modification...");

for(int i=0;i<r;i++)

{

for(int j=0;j<c;j++)

System.out.print(a[i][j]+" ");

System.out.println();

}

}// end of main

}// end of class.

Similar questions