2

I have two arrays, one is String[] and other is int[]. The values in the integer array correspond to the elements of the String array. For example, the String array contains the names of some teams and another int array contains their points in the league. I can sort the int array using Arrays.sort and I want to sort the String array according to the points and if two teams have same points, I should arrange them alphabetically.

I thing I can make a 2D array but how to sort it then?

AmanArora
  • 2,379
  • 6
  • 19
  • 22
  • You need a class - `Team` with `name` and `point` as attribute. There are lots of such example on internet, and SO itself. Please search for it. – Rohit Jain Sep 23 '13 at 08:31
  • This depends on the domain. If teams exist outside these results, then you need a `Team` class and also `TeamResults` class. – RokL Sep 23 '13 at 08:35
  • You can use a Map instead and sort it as described here: http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java – Aliza Sep 23 '13 at 08:37

3 Answers3

4

Consider creating a class:

class Team {
   String name;
   int numPoints;
}

and having an array Team[] teams . You can then create a comparator for these objects that sort based on both String and Integer criteria.

Amir Afghani
  • 37,814
  • 16
  • 84
  • 124
1

You'd have an easy time doing that if you created a class that contains both values for a team, and have the class implement Comparable interface. Then it would be trivial to sort an array of these objects using Arrays.sort.

RokL
  • 2,663
  • 3
  • 22
  • 26
0

Create a class and add two comparators:

class Team{
   private String teamName;
   private int leaguePoints;
   public static final Comparator<Team> BY_NAME = new ByName();
   public static final Comparator<Team> BY_POINTS = new ByPoints();
   private static class ByName implements Comparator<Team>
   {
       public int compare(Team a, Team b)
         return a.name.compareTo(b.name); 
   }
   private static class ByPoints implements Comparator<Team>
   {
      public int compare(Team a, Team b)
         return a.leaguePoints - b.leaguePoints;
   }
}

Then sort the array for this class, using the BY_NAME comparator first and then by BY_POINTS.

Arrays.sort(array, Team.BY_NAME);
Arrays.sort(array, Team.BY_POINTS);

Make sure to use stable sort to preserve the relative order of equal keys (That is if points are equal, then unstable sort like selection sort might mess up the sorted order of team names).

hrv
  • 925
  • 6
  • 13