日期:2014-05-20  浏览次数:20824 次

搞不定:(在已定义好的日期类数组中比较大小、冒泡排序、二分法搜索出定义的日期的数组下标号
在已定义好的日期类数组中比较大小、冒泡排序、二分法搜索出定义的日期的数组下标号
搞不定,难过死了!
都忙活了一下午,还是以失败告终!~
我编译发现在问题就出在binarySearch这个方法里面,我自认为这个方法没有任何问题,为什么就是编译不过去呢~
问题的原因在哪里呢~

public class DateSort
{
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
Date d = new Date(2006, 7, 4);

//冒泡排序
bubbleSort(date);
for(int i=0; i<date.length; i++)
{
System.out.println(days[i]);
}
}

//冒泡排序法:大的往后排,直到发现最大沉底结束,下次搜索范围减去最后一个
public static Date[] bubbleSort(Date[] date)
{
Date temp;
for(int i=date.length-1; i>0; i--) //I的循环条件是数组的第2位也就是i>0
{
for(int j=0; j<i; j++)
{
if(date[j].compare(date[j+1]) > 0)
{
temp = date[j+1];
date[j+1] = date[j];
date[j] = temp;
}
}
}
return date;

}
}


//二分法搜索
public static int binarySearch(Date[] arr, Date d)
{
if(arr.length == 0)
{return -1;}
int head = 0;
int tail = arr.length - 1;
int mid = (head + tail) / 2;
while(head <= tail)
{
if(d.compare(arr[mid]) == 0)
{return mid;}
if(d.compare(arr[mid]) > 0)
{
head = mid + 1;
mid = (head + tail) / 2;
}
if(d.compare(arr[mid]) < 0)
{
tail = mid - 1;
mid = (head + tail) / 2;
}
}
return -1;
}

class Date
{
int year, month, day;
Date(int year, int month, int day)
{
this.year = year;
this.month = month;
this.day = day;
}

//Date日期比较大小
public int compare(Date date)
{
if(this.year > date.year)
{return 1;}
else if(this.year < date.year)
{return -1;}
else
{
if(this.month > date.month)
{return 1;}
else if(month < date.month)
{return 1;}
else
{
if(day > date.day)
{return 1;}
else if(day < date.day)
{return -1;}
else {return 0;}
}
}
}

//重写Object.toString()方法
public String toString()
{
return "Year:Month:Day --" + year + "-" + month + "-" + day;
}

}



------解决方案--------------------
public class DateSort {
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
Date d = new Date(2006, 7, 4);

// 冒泡排序
bubbleSort(date);
for (int i = 0; i < date.length; i++) {
System.out.println(date[i]);
}
System.out.println(binarySearch(date, d));
}

// 冒泡排序法:大的往后排,直到发现最大沉底结束,下次搜索范围减去最后一个
public static Date[] bubbleSort(Date[] date) {
Date temp;
for (int i = date.length - 1; i > 0; i--) // I的循环条件是数组的第2位也就是i>0
{
for (int j = 0; j < i; j++) {
if (date[j].compare(date[j + 1]) > 0) {
temp = date[j + 1];
date[j + 1] = date[j];
date[j] = temp;
}
}
}
return date;

}

// 二分法搜索
public static int binarySearch(Date[] arr, Date d) {
if (arr.length == 0) {
return -1;
}
int head = 0;
int tail = arr.length - 1;
int mid = (head + tail) / 2;
while (head <= tail) {