###### 年糕先生

2015-04-24 17:10 阅读 1.9k

# 自定义类的数组排序和查找问题（自定义Dates类）

`````` public class DateSort{
public static void main(String[] args){
Dates days[] = new Dates[10];
days[0] = new Dates(2013,3,1);      // 初始化日期数组，任意赋值
days[1] = new Dates(2014,3,1);
days[2] = new Dates(2013,4,5);
days[3] = new Dates(2014,5,28);
days[4] = new Dates(2012,8,9);
days[5] = new Dates(2001,12,11);
days[6] = new Dates(2005,10,10);
days[7] = new Dates(2008,8,8);
days[8] = new Dates(2015,9,29);
days[9] = new Dates(1992,1,1);

Dates day = new Dates(2015,9,29);

System.out.println("未排序");
for(int i = 0;i<10;i++){            //输出数组，未排序
days[i].display();
}

for(int i = 0;i < days.length;i++){
for(int j = i+1;j < days.length;j++){
if(days[i].compare(days[j]) == -1){
Dates d = days[i];
days[i] = days[j];
days[j] = d;
}
}
}

System.out.println("\n排序以后");

for(int i = 0;i<10;i++){            //排好序，输出数组
days[i].display();
}

//二分法查找特定Day
int start = 0;
int end = days.length-1;
int m = (start+end)/2;
while(start<=end){
if(days[m].compare(day) == 0){
System.out.println("找到了与day相同的日期，下标i为：" + m);
break;
}
if(days[m].compare(day) == 1){
end = m-1;
}
if(days[m].compare(day) == -1){
start = m+1;
}
m = (start+end)/2;

if(start == end && days[m].compare(day) != 0)
System.out.println("No Found");
}
}
}

class Dates{
int year,month,day;
Dates(int y,int m,int d){
year = y;
month = m;
day = d;
}

public int compare(Dates 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 void display(){
System.out.println(year + "-" + month + "-" + day);
}

}
``````

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享