if input is given like (5,4,6,3) it returns 4,5,3,6 but i want it to return like 3,4,5,6....kindly help.

import java.util.Scanner;

public class sort
{
    public static void main(String args[])
    {
        int rows;
        int cols;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter number of rows u want in matrix ");
        rows=input.nextInt();
        System.out.println("Enter number of columns u want in matrix ");
        cols=input.nextInt();
        int Numbers[][]=new int[rows][cols];
        int temp;
        //get input
        System.out.println("Enter integer values ");
        for (int i=0;i<rows;i++)
        {
            for(int j=0;j<cols;j++)
            {
           Numbers[i][j]=input.nextInt();
        }
    }
    for(int i=1;i<rows;i++)
        {

            for(int a=1;a<cols;a++)
            {
                for(int j=1;j<cols-1;j++)
                if(Numbers[i][j]>Numbers[i][j+1])
                {
                    temp =  Numbers[i][j+1];
                    Numbers[i][j+1] = Numbers[i][j];
                    Numbers[i][j] = temp;

                }
            }
        }
       /*for(int i=0;i<rows;i++)
        {

            for(int j=0;j<cols-1;j++)
            {
                if(Numbers[i][j]>Numbers[i][j+1])
                {
                    temp =  Numbers[i][j];
                    Numbers[i][j] = Numbers[i][j+1];
                    Numbers[i][j+1] = temp;

                }
            }
        }*/
        System.out.println("sorted numbers in ascending order are : ");
        for (int i=0;i< rows;i++)
        {
            for (int j=0;j< cols;j++)
            {
               System.out.print(Numbers[i][j]+" ");
            }
        System.out.println();
}
}
}

Here you can see different algoritms for sorthing array's so you can sort row by row with this algoritms. Link.

You need to decide what you mean by sorting a 2D matrix. The code you have sorts each row individually - which is one passible answer, but it looks like you may want to sort all the values, regardless of rows or columns, in which case I have to ask "why bother with a 2D data structure in the first place?"

This article has been dead for over six months. Start a new discussion instead.