java - 冒泡排序 (泛型版)
2017-06-28 本文已影响17人
萤火之森ss
首先定义一个接口
public interface BubbleSort {
public <T extends Comparable<T>> T[] sore(T[] list);
}
下面是他的实现类
public class BubbleImpl implements BubbleSort {
@Override
public <T extends Comparable<T>> T[] sore(T[] score) {
for(int i = 1;i<score.length;i++){ //这里是最多做n-1次的循环,
for(int j = 0;j<score.length -i ; j ++){
if(score[j] .compareTo(score[j+1]) >0){
T temp = score[j];
score[j] = score[j+1];
score[j+1] = temp;
}
}
}
return score;
}
public static void main(String[] args) {
Integer[] s = {1,3,6,34,32,13,56,87,90,78,56,33};
BubbleSort bs = new BubbleImpl();
Integer[] result = bs.sore(s);
System.out.println((Arrays.toString(result)));
}
}
输出:[1, 3, 6, 13, 32, 33, 34, 56, 56, 78, 87, 90]