Sorting two-dimensional array in java

This exercise can be found in the book "Introduction to Java Programming - 8th edition" by Y. Daniel Liang. No copyright infringement intended.


(Sorting two-dimensional array) Write a method to sort a two-dimensional array using following header:
public static void sort(int m[][])
The method performs a primary sort on rows and a secondary sort on columns


  import java.util.Scanner;

public class SortingTwoDimensionalArray
{
  public static int[][] sort(int[][] m)
  {
    for (int i =0;i<m.length;i++)
    {
      for (int j =0;j<m.length-1;j++)
      {
      if (m[j][0>m[j+1][0])
      {
        int temp = m[j][0];
        int temp1 = m[j][1];
        m[j][0]= m[j+1][0];
        m[j][1]= m[j+1][1];
        m[j+1][0= temp;
        m[j+1][1= temp1;
      }
      
      if (m[j][0== m[j+1][0])
      {
        if(m[j][1>m[j+1][1])
        {
          int temp3 = m[j][1];
          m[j][1= m[j+1][1];
          m[j+1][1= temp3;
        }
      }

      }
    }
    return m;
  }
  //Just a test
  public static void main (String[] args)
  {
    int[][] m = { {4,2},{1,7},{4,5},{1,2},{1,1},{4,1}};
    sort(m);
    for (int i =0;i<m.length;i++)
    {
      for (int j =0;j<m[i].length;j++)
      {
        System.out.print(m[i][j" ");  
      }
      System.out.println();
    }
  }
}


No comments :

Post a 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