//sortTest.java -- by tsaiwn@csie.nctu.edu.tw import java.io.*; import java.util.*; class Stu implements Comparable { long sid; double height; double wet; Stu(long a, double b, double c) {sid=a; height=b; wet=c;} public int compareTo(Object o2){ Stu b = (Stu) o2; if(sid > b.sid) return 1; // ascending order else if(sid < b.sid) return -1; return 0; } }; // struct Stu class sortTest { static int yyy[ ] = { 1, 2, 3, 4, 5, 6 }; static Stu x[ ] = { new Stu(921, 175.0, 60.0), new Stu(911, 172.0, 58.0), new Stu(933, 168., 58.), new Stu(915, 168.5, 56.8), new Stu(938, 170.0, 68.5) }; public static void main(String xxx[ ]) { cout.println("Original data .."); print(x); cout.println("After Arrays.sort(x)"); Arrays.sort(x); print(x); SortAA ar3 = new SortAA ( ); cout.println("After Arrays.sort(x, 0, x.length, ar3)"); Arrays.sort(x, 0, x.length, ar3); print(x); // SortBB lee4 = new SortBB( ); cout.println("After Arrays.sort(x, 0, x.length, lee4)"); Arrays.sort(x, 0, x.length, lee4); print(x); } // main static PrintStream cout=System.out; static void print(Stu y[ ]) { for(int i=0; i < y.length; ++i) { cout.println(""+y[i].sid + " " + y[i].height + " " + y[i].wet); } // for cout.println("=== ==="); } } // sortTest class SortAA implements Comparator { public int compare(T aa, T bb) { Stu a = (Stu)aa; Stu b = (Stu)bb; if(a.height < b.height) return 1; // height Descending else if(a.height > b.height) return -1;// compare other field ? if(a.sid > b.sid) return 1; else if(a.sid < b.sid) return -1; return 0; // equals } // compare } // SortAA class SortBB implements Comparator { public int compare(Object aa, Object bb) { Stu a = (Stu)aa; Stu b = (Stu)bb; if(a.wet < b.wet) return 1; // wet Descending else if(a.wet > b.wet) return -1;// compare other field ? if(a.sid > b.sid) return 1; else if(a.sid < b.sid) return -1; return 0; // equals } // compare } // SortBB