算法分析:
- public int compare(Date date)
- {
- /*
- * 1表示大于,0表示等于,-1表示小于 如果传入的年,大于当前的年,返回1,否则返回-1;
- * 如果传入的月,大于当前的月,返回1,否则返回-1; 如果传入的日,大于当前的日,返回1,否则返回-1;
- */
- 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;
- }
以下用例子测试
- /*
- * 比较多个日期大小,并对日期进行排序
- */
- public class TestDate
- {
- public static void main(String[] args)
- {
- Date[] days = new Date[10];
- days[0] = new Date(2008, 8, 9);
- days[1] = new Date(2008, 8, 20);
- days[2] = new Date(2007, 8, 9);
- days[3] = new Date(2007, 11, 9);
- days[4] = new Date(2006, 8, 9);
- days[5] = new Date(2006, 8, 9);
- days[6] = new Date(2005, 8, 9);
- days[7] = new Date(2005, 9, 9);
- days[8] = new Date(2005, 8, 9);
- days[9] = new Date(2009, 9, 9);
- Date.buffSort(days);
- for (int i = 0; i < days.length; i++)
- {
- System.out.println(days[i]);
- }
- }
- }
- // 比较日期大小
- class Date
- {
- int year;
- int month;
- int day;
- public Date(int y, int m, int d)
- {
- this.year = y;
- this.month = m;
- this.day = d;
- }
- public int compare(Date date)
- {
- /*
- * 1表示大于,0表示等于,-1表示小于 如果传入的年,大于当前的年,返回1,否则返回-1;
- * 如果传入的月,大于当前的月,返回1,否则返回-1; 如果传入的日,大于当前的日,返回1,否则返回-1;
- */
- 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;
- }
- // 用冒泡算法排序
- public static Date[] buffSort(Date[] dates)
- {
- Date temp;
- for (int i = dates.length - 1; i > 0; i--)
- {
- for (int j = 0; j < i - 1; j++)
- {
- if (dates[j].compare(dates[j + 1]) > 0)
- {
- temp = dates[j];
- dates[j] = dates[j + 1];
- dates[j + 1] = temp;
- }
- }
- }
- return dates;
- }
- // 重写toString方法
- public String toString()
- {
- return year + "-" + month + "-" + day;
- }
- }
运行结果:
2005-8-9
2005-8-9
2005-9-9
2006-8-9
2006-8-9
2007-8-9
2007-11-9
2008-8-9
2008-8-20
2009-9-9