class Date{
int day,month,year;
Date(int year, int month, int day){
this.day = day;
this.month = month;
this.year = year;
}
public int compare(Date aim){
if (aim.year > year){
return 1;
}else {
if (aim.year < year){
return -1;
}else {
if (aim.month > month){
return 1;
}else {
if (aim.month < month){
return -1;
}else{
if (aim.day > day){
return 1;
}else {
if (aim.day < day){
return -1;
}
}
}
}
}
}
return 0;
}
public String toString(){
return "Day:Month:Year -- " + day + "-" + month + "-" + year;
}
}
public class DateSort {
public static Date[] bubbleSort(Date[] d){
Date temp;
for (int i = 0; i < d.length -1; i++){
for (int j = 0; j < d.length -1; j++){
if(d[j].compare(d[j+1]) < 0){
temp = d[j];
d[j] = d[j+1];
d[j+1] = temp;
}
}
}
return d;
}
//开始定义二分法
public static int search(Date[] day,Date da){
if(day.length == 0){
System.out.print("数组为空");
return -1;
}
int startPos = 0;//起点,也叫低位
int endPos = day.length - 1;//终点,也称高位
while(startPos <= endPos){
int midPos = (startPos + endPos)/2; //int型强行取整数,若不能被整除则小数部分强行被舍弃
if (day[midPos].compare(da) == 0){
return midPos;
}else if(day[midPos].compare(da) > 0){
startPos = midPos + 1;
}else if(day[midPos].compare(da) < 0){
endPos = midPos - 1;
}
}
System.out.println("查找的日期不存在");
return -1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Date[] day = new Date[5];
day[0] = new Date(2015,5,21);
day[1] = new Date(2014,4,21);
day[2] = new Date(2015,4,20);
day[3] = new Date(2014,5,20);
day[4] = new Date(2014,4,20);
System.out.println("------Original------");
for (int i = 0; i < day.length; i++){
System.out.println(day[i]);
}
bubbleSort(day);
System.out.println("------Sort------");
for (int i = 0; i < day.length; i++){
System.out.println(day[i]);
}
System.out.println("------Search------");
Date aim = new Date(2015,4,20);
System.out.println(search(day,aim));//这里返回的是数组中的位置,要从0开始数
}
}
二分法查找对象的引用
最新推荐文章于 2023-03-02 14:26:05 发布