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


Java猫说
1.3k 声望930 粉丝

现架构设计(码农)兼创业技术顾问,不羁平庸,热爱开源,杂谈程序人生与不定期干货。