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

java引用数组二分法排序问题
问题见代码红色字体部分,哪位高手能帮忙解决一下,谢谢哈:)
java code

class Date1{
  int year;
  int month;
  int day;
  Date1 (int y,int m,int d){
  year=y;
  month=m;
  day=d;
  }
  public int compare(Date1 d){
  return year>d.year? 1
  :year<d.year? -1
  :month>d.month? 1
  :month<d.month? -1
  :day>d.day? 1
  :day<d.day? -1:0;
  }
  /*public String toString(){
  return year+"-"+month+"-"+day;
  }*/
  public static Date1 search(Date1[] d,Date1 searchD){/*谁能解释下这两个形参吗?自己写的都摸不着头脑了……不明白这两
  个形参所代表的实质。*/ 
  if(d.length==0)return null;
  int startPos=0;
  int endPos=d.length-1;
  int m=(startPos+endPos)/2;
  while(startPos<=endPos){
  if(searchD.compare(d[m])==0)
  return searchD;
  if(searchD.compare(d[m])>0){
  startPos=m+1;
  }
  if(searchD.compare(d[m])<0){
  endPos=m-1;
  }
  m=(startPos+endPos)/2;
  }
  return searchD;
  }
  }
  public class TestBs{
  public static void main(String[] args){
  Date1 [] d=new Date1 [5];
  d[0]=new Date1(2007,7,8);
  d[1]=new Date1(2008,8,8);
  d[2]=new Date1(2005,8,1);
  d[3]=new Date1(2004,6,3);
  d[4]=new Date1(2008,6,19);
  System.out.print("所要查询的日期:"+Date1.search(d,d[3]));
  }
  }

运行结果:
所要查询的日期:2004-6-3


------解决方案--------------------
Date1[] d 当然是数组了啊 是Date1类型的对象数组,
Date1 searchD 当然是对象了.
Date1 [] d=new Date1 [5]; 
d[0]=new Date1(2007,7,8); 
d[1]=new Date1(2008,8,8); 
d[2]=new Date1(2005,8,1); 
d[3]=new Date1(2004,6,3); 
d[4]=new Date1(2008,6,19); 
你构造了5个对象放在 d 数组里 和 d[3] 作为参数传给search方法


也就是说你用search方法在d[0],d[1],d[2],d[3],d[4 ]5个对象中查找d[3]对象.

------解决方案--------------------
在我的电脑上完全能运行呀,
------解决方案--------------------
2分法查找是需要对数组先做排序的,你这个实现根本找不到目标的位置
------解决方案--------------------
要进行二分查找,必须先排好序,你能找到巧合,你换别的看看你还能不能找到,看看数据结构