This is a BlueJ program on 2-d array where the values in each row are sorted.
Write a program to enter the elements in the
matrix of m X n order and sort each row of the matrix in ascending order.
Sample Input Output
Values Before Sorting
55 4 3 
2 11 2 
65 4 32 
12 89 7 
Values After Sorting
3 4 55 
2 2 11 
4 32 65 
7 12 89
import java.util.*;
class Search
{
    int
arr[][];
    int
m,n,temp,i,j,k;
   
Scanner sc=new Scanner(System.in);
public void take() 
{    
System.out.print("\nEnter no of rows of
the matrix:");
m=sc.nextInt();
System.out.print("\nEnter no of columns
of the matrix:");
n=sc.nextInt();
arr=new int[m][n];
for(i=0;i<=m-1;i++)
{
   
for(j=0;j<=n-1;j++)
    {
    
System.out.print("\nValue:");
    
arr[i][j]=sc.nextInt();
    }
}
}
public void sort()
{
  
for(i=0;i<=m-1;i++)
   {
       
for(j=0;j<=n-2;j++)
       
{
           
for(k=j+1;k<=n-1;k++)
       
{
           
if(arr[i][j] >arr[i][k])
           
{
                 temp=arr[i][j];
                 arr[i][j]=arr[i][k];
                 arr[i][k]=temp;
                }
            }
       
}
    }
}
   
public void display()
    {
       
for(i=0;i<=m-1;i++)
   {
       
for(j=0;j<=n-1;j++)
       
{
           
System.out.print(arr[i][j]+" ");
       
}
       
System.out.println();
    }
   }
public static void main(String args[])throws
Exception
{
    
Search ob=new Search();
    
ob.take();
    
System.out.println("\nValues Before Sorting");
    
ob.display();
    
ob.sort();
    
System.out.println("\nValues After Sorting");
    
ob.display();
    }
}
No comments:
Post a Comment