两个版本的实现:循环,以及递归。
namespace Data
{
int iArray[] = { 3, 8, 1, 6, 2, 5, 4, 9, 7 };
int iArray1[] = { 2,2,18,9,1,3,2,0,19,20,15,6,12 };
int iArray2[] = { 2,1,1,2 };
vector<int>iVector = { 3, 8, 1, 6, 2, 5, 4, 9, 7 };
int iSortedArray[] = { 1,2,3,4,5,6,7,8,9 };
int iSortedArray1[] = { 1,2,30,44,55,61,71,80 };
}
#pragma region Search
namespace Search
{
using namespace Data;
#pragma regionBinarySearch
int BinSearch(intdata[], int left, int right,int search)
{
int index = -1;
while (left <=right)
{
int mid = (left +right) / 2;
if (data[mid] <search)
left = mid + 1;
else if (data[mid]> search)
right = mid - 1;
else
{
index = mid;
break;
}
}
return index;
}
int BinSearchRecursive(intdata[], int left, int right,int search)
{
int index = -1;
if (left <=right)
{
int mid = (left +right) / 2;
if (data[mid] >search)
index = BinSearch(data,left, mid - 1, search);
else if (data[mid]< search)
index = BinSearch(data, mid + 1,right, search);
else
index = mid;
}
return index;
}
void TestBinSearch()
{
int index = -1;
index = BinSearch(iSortedArray, 0,8, 6);
index = BinSearch(iSortedArray1,0, 7, 30);
index =BinSearchRecursive(iSortedArray, 0, 8, 6);
index =BinSearchRecursive(iSortedArray1, 0, 7, 30);
}
#pragma endregion
}
#pragma endregion
#define TEST(uSpace,method)\
{\
using namespace uSpace;\
method;\
}
int main()
{
TEST(Search, TestBinSearch());
return 0;
}