Java冒泡排序(转载)

import java.util.Comparator;

/**
 * 排序器接口(策略模式: 将算法封装到具有共同接口的独立的类中使得它们可以相互替换)
 *
 */
public interface Sorter {

     /**
        * 排序
        * @param list 待排序的数组
        */
       public <T extends Comparable<T>> void sort(T[] list);

       /**
        * 排序
        * @param list 待排序的数组
        * @param comp 比较两个对象的比较器
        */
       public <T> void sort(T[] list, Comparator<T> comp);
}
import java.util.Comparator;

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) {
                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;
                }
            }
        }
    }

}

测试类:

public class TestSorter {

    public static void main(String[] args) {
        Sorter sorter=new BubbleSorter();
        
        Integer [] list={2,3,1,4};
        sorter.<Integer>sort(list);
        for(int i:list){
            System.out.println(i);
        }
        
        
        Integer [] list2={2,3,1,4};
        sorter.<Integer>sort(list2,new Comparator<Integer>() {

            @Override
            public int compare(Integer o1, Integer o2) {
                
                //降序
                return o2-o1;
                //升序
                //o1-o2
            }
        });
        
        for(int i:list2){
            System.out.println(i);
        }
    }
}

本文来源:http://blog.csdn.net/jackfrued/article/details/44921941

posted @ 2017-04-26 16:55  Johnson_wang  阅读(125)  评论(0编辑  收藏  举报