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;
}