Pages

Friday 8 February 2013

MasterExam (SCJP 6). Sorting with a Comparator

From first attempt I didn't answer correctly. I leave this question for my memories.
Original code example:

package mastertest.sort;
import java.util.Arrays;
import java.util.Comparator;

public class Sort {

    public static void main(String[] args) {
        String [] words = {"Good","Bad", "Ugly"};
        java.util.Comparator<String> best = new Comparator<String>(){
            public int compare(String s1, String s2){
                return s2.charAt(1) - s1.charAt(1);
            }
        };
        Arrays.sort(words,best);
        System.out.println(words[0]);
    }
}



In order to understand the logic of sorting i have expanded that code like that:

package mastertest.sort;
import java.util.Arrays;
import java.util.Comparator;

/**
 * @author Alex
 */
public class Sort {

    public static void main(String[] args) {
        String [] words = {"Good","Bad", "Ugly"};
        java.util.Comparator<String> best = new Comparator<String>(){
            @Override
            public int compare(String s1, String s2){
                if((s2.charAt(1) - s1.charAt(1)) > 0)
                   {System.out.println(s2.charAt(1) + " > " + s1.charAt(1));}
                if((s2.charAt(1) - s1.charAt(1)) < 0)
                   {System.out.println(s2.charAt(1) + " < " + s1.charAt(1));}
                return s2.charAt(1) - s1.charAt(1);
            }
        };
        Arrays.sort(words,best);
        System.out.println(words[0]);
        for(String s:words)
         System.out.println(s);
    }
}

Explanation: The Comparator reverses the natural order using second array element:

1. sorting using the array second element:
B[a]d, U[g]ly, G[o]od
2. Reverse the natural order:
[Good, Ugly, Bad]
words[0] is "Good". This is a correct answer.  A good question!

The trick is that:
to retrieve a natural order sequence you must 1st argument - 2nd argument,
to retrieve the reverse order sequence you must 2nd argument - 1st argument.

No comments:

Post a Comment