while 起始位置 <= 终止位置
起始位置
终止位置
查询位置等于(起始+终止)/2
目标值大于查询目录则 起始位置=查询位置等于 +1 即删除左侧,以右侧为全局并重新进行
public class Test20180506{
public static void main(String args[]){Date[] days = new Date[5];
days[0] = new Date (2009,05,01);
days[1] = new Date (2010,05,01);
days[2] = new Date (2011,05,01);
days[3] = new Date (2012,05,01);
days[4] = new Date (2013,05,01);
Date d = new Date (2011,05,01);
System.out.println(binarySearch(days,d));
}
public static int binarySearch(Date[] days, Date d){
if (days.length == 0) return -1;
int starPos = 0;
int endPos = days.length-1;
int m = (starPos+endPos)/2;
while (starPos <= endPos){
if (d.compare(days[m])== 0) return m;
}
if (d.compare(days[m]) > 1) {
starPos = m + 1;
}
if (d.compare(days[m]) < 1){
endPos = m -1 ;
}
return -1;
}
}
class Date{
int year;
int month;
int 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;
}
}