美文网首页Java Core
java - 冒泡排序 (泛型版)

java - 冒泡排序 (泛型版)

作者: 萤火之森ss | 来源:发表于2017-06-28 16:04 被阅读17次

    首先定义一个接口

    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]

    相关文章

      网友评论

        本文标题:java - 冒泡排序 (泛型版)

        本文链接:https://www.haomeiwen.com/subject/levucxtx.html