一个java小程序,排序用的,可是运行就是排不出正确的由小到大的序 public class BubbleSort { public static void main(String[] args) { Date[] date = new Date[5]; date[0] = new Date(2008, 5, 6); date[1] = new Date(2009, 9, 4); date[2] = new Date(2008, 8, 8); date[3] = new Date(2001, 4, 3); date[4] = new Date(2009, 3, 2);
bubbleSort(date); for(int i = 0; i < date.length; i++) { System.out.println(date[i]); } }
public static Date[] bubbleSort(Date[] a) { for(int i =a.length-1; i >= 1; i--) { for(int j = 0; j <= i-1; i++) { if( a[j].compare(a[j+1]) > 0) { Date temp = a[j+1]; a[j+1] =a[j]; a[j] = temp; } } } return a; }
}
class Date { int year, month, day; public Date(int Year, int Month, int Day) { this.year = Year; this.month = Month; this.day = Day; } public int compare(Date a) { return this.year > a.year ? 1 :this.year < a.year ? 0 :this.month > a.month ? 1 :this.month< a.month ? 0 :this.day > a.day ? 1 :this.day < a.day ? 0 : -1; } public String toString() { return "year-month-day:"+year+"-"+month+"-"+day; } }