public class BubbleSort<T extends Comparable>{
public <T> T[] bubbleSort(T[] arr,Comparator<? super T> comparator){
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length-1-i; j++) {
//相邻的两个元素,进行两两比较
if(comparator.compare(arr[j],arr[j+1])>0){
T temp = arr[j];//交换元素
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
}
public class Test {
public static void main(String[] args) {
Integer[] arr = {3, 5, 2, 1, 4};
BubbleSort bubbleSorts = new BubbleSort();//创建对象
arr = (Integer[]) bubbleSorts.bubbleSort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {//通过比较器比较相邻两个元素大小,-1::前小于后;0:相等;正数前大于后
return o1.intValue() - o2.intValue();
}
});
System.out.println(Arrays.toString(arr));
}
}