/*
* 冒泡排序之升级版,可比较整型数组、小数型数组
*
* */
public static <T extends Comparable<T>> void BubbleGeneric(T[] arr) {
T temp;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j + 1].compareTo(arr[i])<0) {
temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
System.out.println("排序后的数组为:" + Arrays.toString(arr));
}
方法调用:
Integer arrint[] = { 10, 2, 6, 9, 8 }; // 数组需要定义为引用类型、泛型参数需传递引用类型。
Double arrddouble[] = {11.0,45.2,23.0,46.0,89.6};
BubbleGeneric(arrddouble);
BubbleGeneric(arrint);