对多个日期排序,然后用二分查找法查找相应的日期(SXT)
- /*
- * 对多个日期排序,然后用二分查找法查找相应的日期(SXT)
- *
- */
- public class TestDateSort
- {
- 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]);
- }
- //查找2006, 7, 4
- Date d = new Date(2006, 7, 4);
- String str = String.valueOf(d);
- System.out.println(binarySearch(days, d));
- }
- //对日期排序
- 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 int binarySearch(Date[] days, Date d)
- {
- if (days.length == 0)
- return -1;
- int startPos = 0; //起始位置
- int endPos = days.length - 1; //结尾位置
- int m = (startPos + endPos) / 2; //二分点
- while (startPos <= endPos)
- {
- if (d.compare(days[m]) == 0) //比较日期,等于表示找到
- return m;
- if (d.compare(days[m]) > 0) //大于0,向后半部分继续二分
- {
- startPos = m + 1;
- }
- if (d.compare(days[m]) < 0) //小于0,向前半部分继续二分
- {
- endPos = m - 1;
- }
- m = (startPos + endPos) / 2;
- }
- return -1;
- }
- }
- //日期比较
- class Date
- {
- int year, month, day;
- Date(int y, int m, int d)
- {
- year = y;
- month = m;
- day = d;
- }
- //比较日期
- /*
- * 1表示大于,0表示等于,-1表示小于 如果传入的年,大于当前的年,返回1,否则返回-1;
- * 如果传入的月,大于当前的月,返回1,否则返回-1; 如果传入的日,大于当前的日,返回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;
- }
- }