Sorting a Two-dimensional Array in Java

Problem:

In a simple java problem, create a two-dimensional array, and fill it with random numbers. Then sort it.


Solution:


import java.util.Scanner;
public class TwoDimensional
{
  public static void main (String[] args)
  {
    int[][] nums = { {6,4,8,1},

                      {64,76,1,7},

                      {43,87,23,45},

                      {100,56,233,5}};
    int temp =0;//For later use
    int j=0,k =0;
    for (int i =0;i<nums.length*nums[0].length;i++)
    {
      for (j =0;j<nums.length;j++)
      {
        for (k =0;k<nums[j].length-1;k++)
        {
          if (nums[j][k] > nums[j][k+1])
          {
            temp = nums[j][k];
            nums[j][k] = nums[j][k+1];
            nums[j][k+1] = temp;
          }
        }
        if (j != nums.length-1 && nums[j][k] > nums[j+1][0])
        {
          temp = nums[j][k];
          nums[j][k] = nums[j+1][0];
          nums[j+1][0] = temp;
        }
      }
    }
    for (int i = 0;i<nums.length;i++)
    {
      for (j =0;j<nums[i].length;j++)
      {
        System.out.print(nums[i][j] +" ");
      }
      System.out.println();
    }
  }
}


1 comment :

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact