/*
* binarySearch.cpp
* 算法导论 P.23 2.3-5
* Created on: 2011-12-27
* Author: LiChanghai
*/
#include <iostream>
#include <cstdlib>
using namespace std;
template <typename T>
size_t binarySearch(const T array[ ], size_t pBegin, size_t pEnd, T key)
{
//当只有2个元素的时候不再二分,直接比较
if(pBegin+1 == pEnd)
{
if(key == array[pBegin])
return pBegin;
else
if(key == array[pEnd])
return pEnd;
else
{
cerr<<key<<" is not found in this array"<<endl;
exit(0);
}
}
//当只有1个元素时,直接比较
if(pBegin == pEnd)
{
if(key == array[pBegin])
return pBegin;
else
{
cerr<<key<<" is not found in this array"<<endl;
exit(0);
}
}
size_t pDivide = (pBegin + pEnd)/2; //指向中间位置
if(key == array[pDivide])
return pDivide;
else
if(key<array[pDivide])
binarySearch(array, pBegin, pDivide-1, key); //递归调用,在左半部分查找
else
binarySearch(array, pDivide+1, pEnd, key); //递归调用,在右半部分查找
}