Comparator interface: sort by optional order
Public interface comparator <key> int compare (Key V, key W) // compare elements v and W
Example:
Java System sorting)
- Create comparator object)
- Pass the second parameter to array. Sort ()
String [] ;... arrays. sort (); // natural order (natural order )... arrays. sort (A, String. case_insensitive_order); arrays. sort (A, collator. getinstance (New locale ("es"); arrays. sort (A, new briishphonebookorder (); // these three sequence parameters are defined by the comparato <string> object.
Use the comparator interface to select and sort (insertion sort)
public static void sort(Object[] a, Comparator comparator){ int N = a.length; for (int i = 0; i < N;i++) for(int j = i; j > 0 && less(comparator, a[j], a[j-1]); j--) exch(a, j, j-1); }private static boolean less(Comparator c, Object v, Object w){ return c.compare(v, w) < 0; }private static void exch(Object[] a, int i, int j){ Object swap = a[i]; a[i] = a[j]; a[j] = swap; }
Implement the comparator Interface
- Define the class that implements the comparator Interface
- Implement the compare () method
Public class student {public static final comparator <student> by_name = new byname (); public static final comparator <student> by_section = new bysection (); private final string name; private Final int section ;... private Static class byname implements comparator <student> // The byname class implements the comparator interface {public int compare (student V, student W) {return v. name. compareto (W. name) ;}} Private Static class bysection implements comparator <student> // bysection implements the comparator interface {public int compare (student V, student W) {return v. section-w. section ;}}}
The actual comparison is in the Compare overload method.
The comparator interface is a shell that wraps the compare () method.
Princeton University algorithm class algorithm part I week 3 comparator comparators