BinarySearch problems

Hi gang. I'm having a little trouble with my Binary Search algorithm. I was trying to get it to return true is the value is found, and return false, setting position to the index in which the number had to be inserted, but it's not working right. The returned value is not always the proper value to insert into

bool binarySearch(int array[], int Size, int value, int& position)
{
while (position <= Size) {
int mid = (position + Size) / 2; // compute mid point.
if (value > array[mid])
position = mid + 1; // repeat search in top half.
else if (value < array[mid])
Size = mid - 1; // repeat search in bottom half.
else
{
position = mid;
return true; // found it. return position /////
}
}
position = (position - 1);
return false; // failed to find value
}

To test this, I've got a function that generates a list of random numbers (using another pre-defined function random) to generate a unique array of numbers between a certain range.

bool randArray(int array[], int listSize, int lowerList, int upperList)
{
for(int i = 0; i < listSize; i++) //Initalze all member items to 0 (used for passing the 'sorted' list
array[i] = 0;
int RandNum;
int ToPut = 0;
for(int i = 0; i < listSize; i++)
{
do
{
RandNum = random(lowerList, upperList);
} while(binarySearch(array, i, RandNum, ToPut) == true);
for(int j = i + 1; j > ToPut; j--)
swap(array[j], array[j-1]);
array[ToPut] = RandNum;
}
}

This one has really got me stumped. Thank you all so much in advance for your time.

P.s
My first ever post! Yay! I'm a part of a new community :) hehe
[1889 byte] By [Scottyob] at [2007-11-20 11:05:10]
# 1 Re: BinarySearch problems
Are you asking this as an algorithmic challenge or a C++ challenge? Because if it's a C++ challenge, the answer is
#include <algorithm>

bool binarySearch(int array[], int Size, int value, int& position)
{
int* p = std::lower_bound(
&array[0],
&array[Size],
value);
position = p - &array[0];
return position != Size && *p == value;
}
googler at 2007-11-9 1:25:07 >
# 2 Re: BinarySearch problems
more an algorithmic challenge. I'd like to try and see what's wrong with my code and find how to get that to work. I know it must be something simple but I just can't seem to find it.
Scottyob at 2007-11-9 1:26:07 >