【Java貓說】每日演算法:#5-模板(泛型)方法之選擇排序

Java貓說發表於2019-01-19

Java每日演算法

分析

模板函式,泛型引數傳遞排序

·針對各種引數,甚至自定義引數進行排序
·使用Comparable處理所有引數

編碼

@Data
public class Student implements Comparable<Student> {

    private String name;
    private int score;

    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    /**
     * 定義Student的compareTo函式,如果分數相等,則按照名字的字母序排序
     * 如果分數不等,則分數高的靠前
     * @param o
     * @return
     */
    @Override
    public int compareTo(Student o) {
        if (this.score < o.score){
            return -1;
        }else if(this.score > o.score){
            return 1;
        }else{
            return this.name.compareTo(o.name);
        }
    }

    /**
     * 定義Student例項的列印輸出方式
     * @return
     */
    @Override
    public String toString() {
        return "Student: " + this.name + " " + Integer.toString( this.score );
    }

}

模板化選擇排序

public class SelectionSort {

    private SelectionSort(){}

    public static void sort(Comparable[] arr){
        for (int i = 0;i<arr.length;i++){
            int minIndex = i;
            for (int j=i+1;j<arr.length;j++){
                if (arr[j].compareTo(arr[minIndex]) < 0){
                    minIndex = j;
                }
            }
            swap(arr,i,minIndex);
        }
    }

    private static void swap(Object[] arr, int i, int j) {
        Object t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    public static void main(String[] args) {

        // 測試Integer
        Integer[] a = {10,9,8,7,6,5,4,3,2,1};
        SelectionSort.sort(a);
        for( int i = 0 ; i < a.length ; i ++ ){
            System.out.print(a[i]);
            System.out.print(` `);
        }
        System.out.println();

        // 測試Double
        Double[] b = {4.4, 3.3, 2.2, 1.1};
        SelectionSort.sort(b);
        for( int i = 0 ; i < b.length ; i ++ ){
            System.out.print(b[i]);
            System.out.print(` `);
        }
        System.out.println();

        // 測試String
        String[] c = {"D", "C", "B", "A"};
        SelectionSort.sort(c);
        for( int i = 0 ; i < c.length ; i ++ ){
            System.out.print(c[i]);
            System.out.print(` `);
        }
        System.out.println();

        // 測試自定義的類 Student
        Student[] d = new Student[4];
        d[0] = new Student("D",90);
        d[1] = new Student("C",100);
        d[2] = new Student("B",95);
        d[3] = new Student("A",95);
        SelectionSort.sort(d);
        for( int i = 0 ; i < d.length ; i ++ )
            System.out.println(d[i]);
    }

}

地址與程式碼獲取

專案以傳Github,定期更新演算法內容
UncleCatMySelf/java_algorithm

相關文章