public class TestDateSort{ public static void main(String[] args){ Date[] date=new Date[5]; date[0]=new Date(2006,5,4); date[1]=new Date(2006,7,4); date[2]=new Date(2008,5,4); date[3]=new Date(2004, 5, 9); date[4]=new Date(2004, 5, 4); Date d=new Date(2006,7,4); //bubbleDateSort(date); selectionDateSort(date); for(int i=0;i<date.length;i++){ System.out.println(date[i]); } System.out.println(binaryDate(date,d)); } public static void bubbleDateSort(Date[] date){ for(int i=0;i<date.length-1;i++){ for(int j=0;j<date.length-1;j++){ if((date[j].compare(date[j+1])>0)){ Date d=null; d=date[j]; date[j]=date[j+1]; date[j+1]=d; } } } } public static void selectionDateSort(Date[] date){ for(int i=0;i<date.length-1;i++){ for(int j=i+1;j<date.length;j++){ if(date[i].compare(date[j])>0){ Date d=null; d=date[i]; date[i]=date[j]; date[j]=d; } } } } public static void insertDateSort(Date[] date){ } public static int binaryDate(Date[] date,Date d){ int startPos=0; int endPos=date.length-1; int m=(startPos+endPos)/2; while((date[startPos].compare(date[endPos]))<0){ if((date[m].compare(d))==0) return m; if((date[m].compare(d))>0){ endPos=m-1; m=(startPos+endPos)/2; } if((date[m].compare(d))<0){ startPos=m+1; m=(startPos+endPos)/2; } } return -1; } } class Date{ private int year; private int month; private int date; public Date(int year,int month,int date){ this.year=year; this.month=month; this.date=date; } public String toString(){ return "year-month-date:"+year+"-"+month+"-"+date; } public int compare(Date d){ if(this.year<d.year){ return -1; }else if(this.year>d.year){ return 1; }else{ if(this.month<d.month){return -1;}else if(this.month>d.month){ return 1; }else{ if(this.date<d.date){return -1;}else if(this.date>d.date){ return 1; }else{ return 0; } } } } }
时间: 2024-10-16 18:15:47