冒泡排序,人人都会写,但是写一个高格局的冒泡排序就不一样了。
1:定义接口:Sorter
public interface Sorter{
//list:待排序的数组
public <T extends Comparable<T> > void sort(T[ ] list);
public <T> void sort(T [] list,Comparator<T> compa);
}
//创建一个排序的工具类
public class SorterUtils implements Sorter{
@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; } } } }
}