【Java猫说】每日算法:#5-模板(泛型)方法之选择排序
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
相关推荐
zhangxiafll 2020-11-13
anglehearts 2020-08-17
xiaoxiaoCNDS 2020-06-25
TreasureZ 2020-06-16
lantingyue 2020-05-31
iconhot 2020-05-26
luohui 2020-04-29
fraternityjava 2020-04-29
yicuncuntu0 2020-04-19
Justhavefun 2020-02-21
alicelmx 2020-02-13
iconhot 2020-01-28
yicuncuntu0 2019-12-18
wxy0 2019-12-09
丁一鸣的CSDN 2011-06-25
iosJohnson 2019-11-05