/**
*定义一个排序方法接口
**/
import java.util.Comparator;
public interface Bubble {
/**
* 排序
* @param list 待排序数组
*/
public <T extends Comparable<T>> void sort(T[] list);
/**
* 排序
* @param list 待排序数组
* @param cmp 比较俩个对象的比较器
*/
public <T> void sort(T[] list,Comparator<T> comp);
}
//实现方法接口
import java.util.ArrayList;
import java.util.Comparator;
import java.util.stream.Stream;
public class BubbleSort implements Bubble {
@Override
public <T extends Comparable<T>> void sort(T[] list) {
boolean swapped = true;
for (int i = 1, len = list.length; i < len && swapped; i++) {
swapped = false;
for (int j = 0; j < len - i; j++) {
if (list[j].compareTo(list[j + 1]) > 0) {
T temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
swapped = true;
}
}
}
}
@Override
public <T> void sort(T[] list, Comparator<T> comp) {
boolean swapped = true;
for (int i = 1, len = list.length; i < len && swapped; i++) {
swapped = false;
for (int j = 0; j < len - i; j++) {
if (comp.compare(list[j], list[j + 1]) > 0) {
T temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
swapped = true;
}
}
}
}
}
//测试类
package sort;
public class TeatSort {
public static void main(String[] args){
Integer[] list={1,2,31,2,15,68};
new BubbleSort().sort(list,(o1,o2)->{
if(o1>o2)
return 1;
else
return 0;
});
for(int i=0;i<list.length;i++){
System.out.println(list[i].intValue());
}
String[] listStr={"1","8","4","6","9"};
new BubbleSort().sort(listStr);
for(int i=0;i<listStr.length;i++){
System.out.println(listStr[i]);
}
}
}