1.遞歸方式對有序表進行折半查找
template<class E, class K> // SortedList模板類,E元素類型,K關鍵碼類型
int SortedList<E, K>::BinarySearch(const K x, int low, int high)
{
int mid = 0;
if(low <= high)
{
mid = (low + high)/2;
if(x > Element[mid].key)
mid = BinarySearch(x, mid+1, high);
else if(x < Element[mid].key)
mid = BinarySearch(x, low, mid-1);
}
return mid;
}
2.非遞歸方式對有序表進行折半查找
template<class E, class K>
int SortedList<E, K>::BinarySearch(const K x)const
{
int high = m_iCurrentSize - 1;
int low = 0;
int mid = 0;
while(low <= high){
mid = (low + high)/2;
if(x > Element[mid].key)
low = mid + 1;
else if(x < Element[mid].key)
high = mid - 1;
else return mid;
}
return 0;
}