排序入门:排序类的模板&定义一个可排序的数据类型

排序算法类的模板:

public class Example
{
    public static void sort(Comparable[] a)
    { /* */ }
    
    #对元素进行比较
    private static boolean less(Comparable v,Comparable w)
    { return v.compareTo(w)<0 }
    
    # 将元素交换位置
    private static void exch(Comparable[] a,int i,int j)
    { Comparable t=a[i];a[i]=a[j];a[j]=t }
    
    #在单行中打印数组
    private static void show(Comparable[] a)
    {
        for (int i=0;i

定义一个可排序的数据类型

创建自己的数据类型时,我们只要实现Comparable接口就能保证用例代码可以将其排序。要做到这点,需要实现一个compareTo() 方法来定义目标类型对象的自然次序

CASE1:
创建一个可排序的数据类型

package rankCore;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class dateRank implements Comparable {
    private static final Logger logger = LoggerFactory.getLogger(dateRank.class);
    private final int day;
    private final int month;
    private final int year;

    public dateRank(int d, int m, int y) {
        day = d;
        month = m;
        year = y;
    }

    public int getDay() {return day;}

    public int getMonth() {return month;}

    public int getYear() {return year;}

    public int compareTo(dateRank o) {
        if (this.year > o.year) { return 1; }
        if (this.year < o.year) { return -1; }
        if (this.month > o.month) { return 1; }
        if (this.month < o.month) { return -1; }
        if (this.day > o.day) { return 1; }
        if (this.day < o.day) { return -1; }
        return 0;
    }

    @Override
    public String toString() {
        return month + "/" + day + "/" + year;
    }
}

测试用例:

import static java.util.Arrays.sort;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rankCore.dateRank;

public class dateRankTest {
    private static final Logger logger = LoggerFactory.getLogger(dateRankTest.class);

    public static void main(String args[]) {
        dateRank[] dateranks = new dateRank[2];
        dateranks[0] = new dateRank(15, 4, 1991);
        dateranks[1] = new dateRank(05, 4, 1991);
        sort(dateranks);
        for(int i=0; i

你可能感兴趣的:(排序入门:排序类的模板&定义一个可排序的数据类型)