Untitled
By: a guest | Mar 21st, 2010 | Syntax:
C++ | Size: 2.00 KB | Hits: 93 | Expires: Never
//Here is the function that takes 1 generic array argument, 1 size of the array generic argument, and 1 value which represents what is being looked for.
int binarySearch(int myArray[], int totalElements, int value)
{
int beginingElement = 0;//represents the starting poing of the array subscript 0
int lastElement = totalElements - 1;//represents the last point in the array subscript last spot minus 1
int middle;//Represents the middle point of the array
int position = -1;//this is the return once the value was found. It is set to -1 cause this lets us know that the value has not yet been found.
bool found = false;//This represents weather the value has been found yet or not as a true false boolean.
while(found == false && beginingElement <= lastElement)//As long as the value has not been found "AND" the begining subscript is not greater than the last in the array
{
//adds subscript 0 and last then divides by 2. Remainder is set to middle.
middle = (beginingElement + lastElement) / 2;
//if the middle of the array is equal to the value we are looking for then found is set to true
//and the position is changed from -1 to whatever the subscript is for the middle variable.
if(myArray[middle] == value)
{
found = true;
position = middle;
}
//otherwise if the value we are looking for is less than the middle value
//we take that middle value and go to the spot right before it and then make that the
//new last element in turn cutting again the array in half.
else if(myArray[middle] > value)
{
lastElement = middle - 1;
}
//otherwise if the value we are looking for is bigger than the middle then
//we take the middle and go to the spot right after it and make that our new
//starting spot again cutting the array in half.
else
{
beginingElement = middle + 1;
}
}
//lastly once we loop back to the top of the while loop and the found variable is now set to true
//the position element is stored and returned.
return position;
}