public class GenericSort {
public static void show() {
Integer[] intArray = {new Integer(2),new Integer(4),new Integer(3)};
Double[] doubleArray = {new Double(2.5),new Double(6.4),new Double(3.3)};
Character[] charArray = {new Character('a'),new Character('q'),new Character('c')};
String[] stringArray = {"liu","lu","hhh"};
sort(intArray);
sort(doubleArray);
sort(charArray);
sort(stringArray);
System.out.print("sorted integer objects: ");
printList(intArray);
System.out.print("sorted Double objects: ");
printList(doubleArray);
System.out.print("sorted char objects: ");
printList(charArray);
System.out.print("sorted string objects: ");
printList(stringArray);
}
public static > void sort(E[] list) { //可以对任何对象类型的数组进行排序
E currentMin;
int currentMinIndex;
for(int i = 0; i < list.length -1 ;i++) {
currentMin = list[i];
currentMinIndex = i;
for (int j = i+1 ; j < list.length; j++) {
if(currentMin.compareTo(list[j])>0) {
currentMin = list[j];
currentMinIndex = j;
}
}
if(currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
public static void printList(Object[] list) {
for(int i = 0; i< list.length ; i++)
System.out.print(list[i]+" ");
System.out.println();
}
}