-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsorter.java
32 lines (32 loc) · 1.02 KB
/
sorter.java
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
28
29
30
31
32
public interface Comparator {
//Return a negative number if x comes before y,
// a positive number if y comes before x,
// and zero if there is no ordering constraint
public static int compare(Object x, Object y);
}
public class IntegerComparator implements Comparator {
public static int compare(Object x, Object y) {
return (Integer) x - (Integer) y;
}
}
public class StringComparator implements Comparator {
public static int compare(Object x, Object y) {
return ((String)x).compareTo((String)y);
}
}
public class Sorter {
public static void sort(Object[] data, Comparator comp) {
for (int i=data.length-1; i >= 1; i--) {
// in each iteration through the loop
// swap the largets value in data[0]..dta[i] into position i
int indexOfMax = 0;
for (int j=1; j <= i; j++) {
if (comp.compare(data[j], data[indexOfMax]) > 0)
indexOfMax = j
}
Object temp = data[i];
data[i] = data[indexOfMax];
data[indexOfMax] = tmp;
}
}
}