怎么回事?怎么都找不出来!可就是有错误
class Date {
public int year, month, day;
Date(int y, int m, int d) {
year = y;
month = m;
day = d;
}
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;
}
}
public class TestDateSort {
public static void main(String[] args) {
Date[] days = new Date[5];
days[0] = new Date(2006, 5, 6);
days[1] = new Date(2006, 7, 3);
days[2] = new Date(2003, 8, 1);
days[3] = new Date(2006, 5, 1);
days[4] = new Date(2003, 1, 1);
Date d = new Date(2006, 5, 1);
bubbleSort(days);
for(int i=0; i<days.length; i++) {
System.out.println(days[i]);
}
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(days[m].compare(d) == 0) return m;
if(days[m].compare(d) > 0) {
endPos = m - 1;
}
if(days[m].compare(d) < 0) {
startPos = m + 1;
}
m = (startPos + endPos) / 2;
}
return -1;
}
}
}
[解决办法]
public class TestDateSort {
public static void main(String[] args) {
Date[] days = new Date[5];
days[0] = new Date(2006, 5, 6);
days[1] = new Date(2006, 7, 3);
days[2] = new Date(2003, 8, 1);
days[3] = new Date(2006, 5, 1);
days[4] = new Date(2003, 1, 1);
Date d = new Date(2006, 5, 1);
bubbleSort(days);
for (int i = 0; i < days.length; i++) {
System.out.println(days[i].year);
}
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 (days[m].compare(d) == 0)
return m;
if (days[m].compare(d) > 0) {
endPos = m - 1;
}
if (days[m].compare(d) < 0) {
startPos = m + 1;
}
m = (startPos + endPos) / 2;
}
return -1;
}
}
class Date {
public int year, month, day;
Date(int y, int m, int d) {
year = y;
month = m;
day = d;
}
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;
}
}