java - 冒泡排序 (泛型版)

首先定义一个接口

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]

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容