-4

I have 7 letters on my screen, A (X = 24, y = 27), B (X = 38, y = 27), C (X = 54, y = 26), D (X = 18, y = 59), E (X = 33, y = 58), F (X = 49, y = 58) and G (X = 63, y = 57) when I put my coordinates in an ArrayList they enter randomly, I want to sort them in the order they are displayed, where I sort them as I go down the Y axis, so for example I get all coordinates on Y = 27 sort them by X where the smallest is put in front of the ArrayList etc below is my code:

private static void sort(ArrayList<BoxLetter> letters){


    for(int i = 0; i < letters.size(); i++){

        for(int j = letters.size() -1; j > i; j--){

                if(letters.get(i).getCentroid().y > letters.get(j).getCentroid().y){

                    if(letters.get(i).getCentroid().x > letters.get(j).getCentroid().x){

                        BoxLetter temp = letters.get(i);
                        letters.set(i, letters.get(j));
                        letters.set(j, temp);
                        Logger.printMessage("Sorting");
                    }
               }
        }
    }
 }

When I run my code the output is ADBCEFG but I expect it to output ABCDEFG My question is, How can I sort the list in the form ABCDEFG in Java 7?

Bill F
  • 723
  • 11
  • 23
Sandy McCathy
  • 63
  • 1
  • 10
  • And your question is... – Joe C May 14 '17 at 19:07
  • you are not clear what you are asking for. – Vishrant May 14 '17 at 19:08
  • its right there I want it to output in the form ABCDEFG – Sandy McCathy May 14 '17 at 19:11
  • I understand that for the X, Y numbers of the letters you are providing, you want the algorithm to order them as ABCDEFG. However, it is not clear to me how you could get that ordering from the given example. Please provide the logic for such ordering. If you want to order first by `y` and then `x`, then CBAGFED is the correct output. – fps May 14 '17 at 20:37

1 Answers1

2

Instead of reimplementing sorting, just let Java do the heavy lifting for you by implementing a Comparator. With Java 8, this should be quite elegant:

letters.sort(Comparator.comparingInt(a -> a.getCentroid().y)
                       .thenComparingInt(a -> a.getCentroid().x));

EDIT:
Earlier Java version may require some more boiler-plate code, but the concept remains similar:

Collections.sort(letters, new Comparator<BoxLetter>() {
    @Override
    public int compare(BoxLetter a, BoxLetter b) {
        int cmp = Integer.compare(a.getCentroid().y, b.getCentroid().y);
        if (cmp != 0) {
            return cmp;
        }
        return Integer.compare(a.getCentroid().x, b.getCentroid().x);
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350