-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomparator
More file actions
28 lines (27 loc) · 940 Bytes
/
comparator
File metadata and controls
28 lines (27 loc) · 940 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//using comparators
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 seap = a[i]; a[i]=a[j]; a[j]=swap;
}
//implement a comparator
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> {
public int compare(Studetn v, Student w) {
return v.name.compareTo(w.name); }
}
private static class BySection implements Comparator<Studetn> {
public int compare(Student v, Student w) {
return v.section - w.section;
}
}