0

I need to sort a move list for an abstract game. The move list is an array of type int. Each move requires nine elements in the array one of which is the score value that I wish to sort on.

I see that Java has a java.util.Arrays.sort(int[]) method but I don’t see how this could be useful due to the move list multiple element structure.

I don’t want to write a bubble sort because sort speed is critical.

Does java have any fast sort functions that can serve my purpose? i.e. Be used to sort multi-element records in an int array using one element as the sort value?

  • Potential duplicate of: http://stackoverflow.com/questions/4907683/sort-a-two-dimensional-array-based-on-one-column – CollinD Jan 10 '17 at 17:51
  • 1
    Why not create an object called `Move` that holds 9 `int` properties and then have it `implements` `Comparable`. Then you could put your `Move` objects in a `List` and do `Collections.sort(`whatever you call your list`);` – CraigR8806 Jan 10 '17 at 18:00
  • I though about using objects but was told I would take a big performance hit. The sorting process must be a fast as possible for this application. – user3396618 Jan 10 '17 at 18:06
  • I think what CollinD points you to should work. Make your move a row in a 2-D array. – Kedar Mhaswade Jan 10 '17 at 18:07
  • 1
    The performance hit would be very minimal, you're still storing generally the same amount of memory. To be honest, readability of code is>performance anyway. If you ever have to go back or anyone else needs to refactor your code, it will be much clearer as to what each of those values means rather than just having arbitrary `int`s lined up inside of an array. – CraigR8806 Jan 10 '17 at 18:09

1 Answers1

0

You could do something like this:

 public class Move implements Comparable{


      private int score,prop1,prop2;//...

      public int compareTo(Move move) {
          return this.score>move.score?1:this.score<move.score?-1:0;
      }
 }

Implementing Comparable will allow you to sort a Collection of Move objects like so:

List<Move> moves = new ArrayList<>();
//add all of your Move objects to moves list
Collections.sort(moves);

Your List will now be sorted based on score

CraigR8806
  • 1,584
  • 13
  • 21