用二分法對引用類型進行查找
首先,我們都清楚,如果想在一堆數據中進行查找的話,這些數據最好都是排好序的,這樣才方便查找。
也就是說查找,一般是建立在排序的基礎上,下面我們就拿上篇博文中的例子:
http://www.aygfsteel.com/jialisoft/archive/2012/10/05/389054.html
對Date這個引用類型進行查找
[java] view plaincopy
- public class TestSearchDate
- {
- public static void main(String args[])
- {
- Date[] d=new Date[5];
- d[0]=new Date(2006,5,4);
- d[1]=new Date(2006,7,4);
- d[2]=new Date(2008,5,4);
- d[3]=new Date(2004,5,9);
- d[4]=new Date(2004,5,4);
- bubbleSort(d);
- for(int i=0;i<=d.length-1;i++)
- {
- System.out.println(d[i]);
- }
- Date oneDate=new Date(2008,5,4); //查找這個日期中排序序列的什么位置
- System.out.println(Search(oneDate,d));
- }
- //用冒泡排序法,進行排序
- public static void bubbleSort(Date[] d)
- {
- for(int i=d.length-1;i>=1;i--)
- {
- for(int j=0;j<i;j++)
- {
- if(d[j].Compare(d[j+1])>0)
- {
- Date temp;
- temp=d[j];d[j]=d[j+1];d[j+1]=temp;
- }
- }
- }
- }
- //用二分法查找oneDate在d這個Date數組的什么位置
- public static int Search(Date oneDate,Date[] d)
- {
- Date temp;
- int current;
- int startPos=0;
- int endPos=d.length-1;
- current=d.length/2;
- while(startPos<=endPos)
- {
- if(oneDate.Compare(d[current])==0)
- {
- return current; //找到了,返回當前的索引
- }
- else if(oneDate.Compare(d[current])>0)
- {
- startPos=current+1;
- }
- else
- {
- endPos=current-1;
- }
- current=(startPos+endPos)/2;
- }
- return -1; //表示沒有找到
- }
- }
- class Date
- {
- 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;
- }
- //重寫toString方法
- public String toString()
- {
- return "year-month-day:"+year+"-"+month+"-"+day;
- }
- }
主要看就是其中的二分法查找,我想大家一看就明白。
運行結果如下: