用冒泡算法实现对日期的排序
1 //日期类,包含年月日的信息。重写toString 2 //方法,输出年月日信息。 3 public class Date { 4 5 public int year ,month,day; 6 7 public Date(int year,int month,int day){ 8 this.year = year; 9 this.month = month; 10 this.day = day; 11 } 12 13 public String toString(){ 14 return "year,month,day:"+year+" "+month+" "+day; 15 } 16 }
1 public class TestBubbleSort { 2 3 public static void main(String[] args){ 4 5 Date[] dates = new Date[5]; 6 7 dates[0] = new Date(2012,6,1); 8 dates[1] = new Date(2013,6,2); 9 dates[2] = new Date(2012,7,3); 10 dates[3] = new Date(2013,6,1); 11 dates[4] = new Date(2012,7,2); 12 13 BubbleSort(dates); 14 15 for(int i = 0;i<dates.length;i++){ 16 System.out.println(dates[i].toString()); 17 } 18 } 19 20 21 //Compare方法,若d1<d2返回-1,d1=d2返回0,否则返回1. 22 public static int Compare(Date d1,Date d2){ 23 24 if(d1.year>d2.year ){ 25 return 1; 26 }else if (d1.year < d2.year ){ 27 return -1; 28 }else if(d1.month > d2.month){ 29 return 1; 30 }else if(d1.month < d2.month ){ 31 return -1; 32 }else if(d1.day > d2.day ){ 33 return 1; 34 }else if(d1.day < d2.day ){ 35 return -1; 36 }else{ 37 return 0; 38 } 39 } 40 41 public static Date[] BubbleSort(Date[] dates){ 42 int length = dates.length; 43 Date temp = null; 44 45 for(int i = length-1;i>=1;i--){ 46 for(int j = 0;j<i;j++){ 47 if(Compare(dates[j],dates[j+1])==1){ 48 temp = dates[j]; 49 dates[j] = dates[j+1]; 50 dates[j+1] = temp; 51 } 52 } 53 } 54 55 return dates; 56 } 57 }