废话不多说,直接上代码吧:
public interface Sorter(){
public <T extends Comparable<T>> void sort(T[] list);
public <T> void sort(T[] list,Comparator<T> comp);
}
public class BubbleSorter 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)i{
if(list[j].conpareTo(list[j+1])>0){
T temp = list[j];
list[j] = list[j+1];
list[j+1]=temp;
swapped=true;
}
}
}
}
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;
}
}
}
}
}
此方法使用了策略模式,将算法封装到具有共同接口的类中,使得他们可以互相替换。