I am testing the different sort methods (Selection, bubble insertion) and I am trying to use Comparator at the same time.
So far I have two classes; Main and Selectionsort.
My main looks like this:
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
String[] anArray = {"Ludo", "matador", "ChessTitan", "Rottefælden"};
for (int i=0; i<anArray.length-1; i++) {
for (int j=i+1; j<anArray.length; j++) {
if (anArray[j].compareTo(anArray[i]) < 1) {
String temp = anArray[i];
anArray[i] = anArray[j];
anArray[j] = temp;
}
}
}
for (String string : anArray) {
System.out.println(string);
}
}
}
And my selectionSort looks like this:
public class SelectionSort implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
What I want to do is use my Comparator when I use selection sort.
How is this possible?
replace this line:
with this:
where
comparatoris an instance of the comparator you want to use.Since your Comparator has no state, you’ll probably want to assign it to a static final field.
So now the above code would read
Here’s a solution for your last question. Create two overloaded static methods, one with a Comparator, one without, then also create a Comparator that uses the natural order (amazingly no such thing is available to my knowledge in the JDK). Something like this: