将冒泡排序写成面向对象的形式
使用泛型进行比较大小的时候 需要注意 将<T>写成<T extends Comparable>,才能使用compareTo函数!
详情:https://blog.youkuaiyun.com/hgtjcxy/article/details/81389018?utm_source=blogxgwz1
下面是我自己编写的代码
UtilSort类
public class UtilSort<E extends Comparable> {
private E []arr;
public UtilSort(){}
public UtilSort(E arr[]){
this.arr = arr;
}
public void maopaoSort(){
for(int i=0;i<arr.length;i++) {
for(int j = 0;j<arr.length-1-i;j++) {
if(arr[j].compareTo(arr[j+1])>0) {
E temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
public void printArr() {
System.out.print("经过冒泡排序后的数组 : arr [");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("]");
}
}
测试类
/***
* 测试冒泡排序 面向对象编程
*
* @author meng
*
*/
public class Test {
public static void main(String[] args) {
test01();
}
public static void test01() {
Integer[] arr = { 2, 5, 1, 3, 4 };
Double []arr1 = {3.5,2.88,1.32,3.4};
UtilSort u = new UtilSort(arr);
u.maopaoSort();
u.printArr();
UtilSort<Comparable> u1 = new UtilSort<Comparable>(arr1);
u1.maopaoSort();
u1.printArr();
}
}
需要注意数组实例化的时候 需要使用包装类,详情参照:https://blog.youkuaiyun.com/FBB360JAVA/article/details/79126641