Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort 3 parallel arrays?

I currently have 3 arrays of information and am unsure of how to sort them based on one of the values:

int[] rank = { 1, 3, 4, 2, 5 };
String[] game = { "Snake", "Mines", "Fragged", "Siege", "Tower" };
int[] year = { 1980, 1983, 1981, 1995, 1992 };

I'm wanting to sort it by rank, and I've seen many examples of people using comparators to sort 2 parallel arrays, but I haven't seen any example for sorting more than 2.

My first thought was to create a class with a variable for each and then sort that object, but is an extra class really necessary for a sort?

like image 369
WilliamShatner Avatar asked Dec 06 '22 10:12

WilliamShatner


2 Answers

My first thought was to create a class with a variable for each and then sort that object, but is an extra class really necessary for a sort?

It's not strictly necessary - you could definitely write some code to avoid it if you really wanted to. However, I'd say it's a thoroughly good thing.

You don't really have three collections of separate items here: you have one collection of items, each of which has three properties. So make your code match that. Whenever you find you have parallel collections, such that a[0] is related to b[0] is related to c[0] etc, you should think about encapsulating that information in a separate class. It will make your code much easier to maintain, and enforces more consistency.

For example, it would make no sense for those arrays to have different lengths: but there's nothing inherent in the declaration to stop that. If you have one collection, you can't possibly have different numbers of items for the different properties, precisely because you've got one collection.

like image 130
Jon Skeet Avatar answered Dec 23 '22 07:12

Jon Skeet


I think creating a new class would be the cleanest solution. You could manually implement a new sort function to duplicate swaps to the other 2 arrays whenever you apply a swap to the first array (rank), but that gets messy very quickly.

Something like the following would be all you need:

public class Game implements Comparable<Game>{
    private int rank = 0;
    private int year = 0;
    private String name = "";
    ...
    // Constructor +
    // Usual getters and setters here
    ..
    public int compareTo(Game anotherGame) {
       return this.rank - anotherGame.getRank();
    }
}

And then you can simply do:

List<Game> games = new ArrayList<Game>();
...
// Add some games to your games list
...
Collections.sort(games);
like image 32
sampson-chen Avatar answered Dec 23 '22 08:12

sampson-chen