package jave;
/*日期排序*/
public class DataSort {
public static void main(String[] args) {
Date[] days = new Date[5];
days[0] = new Date(2006, 5, 4);
days[1] = new Date(2006, 7, 4);
days[2] = new Date(2008, 5, 4);
days[3] = new Date(2004, 5, 9);
days[4] = new Date(2004, 5, 4);
bubblesort(days);
for(int i = 0; i < days.length; i++) {
System.out.println(days[i]);//将数组里的内容转换成toString输出
}
}
//对日期进行冒泡排序
public static Date[] bubblesort(Date[] a) { //返回类型为数组类型
int len = a.length;
for(int i = len - 1; i >= 1; i--) {
for(int j = 0; j <= i - 1; j++) {
if((a[j].compare(a[j+1])) > 0) {
Date temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
return a;
}
public static class Date {
int year, month, day;
Date(int y, int m, int d){
year = y;
month = m;
day = d;
}
//比较日期大小,先看年份,年份大就返回1,否则返回-1,如果年份相等,再比较月份,以此类推
public int compare(Date date) {
return year > date.year ? 1
: year < date.year ? -1
: month > date.month ? 1
: month < date.month ? -1
: day > date.day ? 1
: day < date.day ? -1 : 0;
}
//重写toString方法
public String toString() {
return "Year:Month:Day -- " + year + "-" + month + "-" + day;
}
}
}
利用冒泡排序对日期进行排序
最新推荐文章于 2022-11-06 17:24:45 发布