1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
void vBinarySearch(int iEnd, int iStart, int iFind, int iArray[], int &iLoc)
{
iLoc = -1;
while (iEnd>=iStart)
{
if (iArray[(iEnd + iStart) / 2] == iFind)
{
iLoc = (iEnd + iStart) / 2;
}
else if (iArray[(iEnd + iStart) / 2] > iFind)
{
vBinarySearch(((iEnd + iStart) / 2) - 1, iStart, iFind, iArray, iLoc);
}
else
{
vBinarySearch(iEnd, ((iEnd + iStart) / 2) + 1, iFind, iArray, iLoc);
}
}
}
int main()
{
int iArray[5] = { 1,2,3,4,5 };
int iFind = 2;
int iLoc = 0;
vBinarySearch(5 - 1, 0, iFind, iArray,iLoc);
std::cout << iLoc;
system("pause");
return 0;
}
|