M
Massimiliano Alberti
Can someone check this? If it's OK, you can use however you want... 
It should search for an element in an array and, if it can't find it, return
the next element.
key is what you are searching, in a *base array of LONG with num elements.
After some tests it seems to work well (the original version was filled with
ASSERTs)
(I will use this function in a bigger look-for-or-insert function)
Some notes:
The function returns the index of the element.
2, 2, 2, 3. Search for 2, it will return the second one (index = 1)
1, 2, 2, 4. Search for 2, it will return the first one (index = 1)
But it should always return the first bigger-than-key element, if it can't
find key (this is very important. I have to insert a new element in that
place, and I want the array to be still ordered after the insertion)
If key > max(all-the-elements) then the function returns -1;
int FindGreaterOrEqual(LONG key, LONG *base, size_t num)
{
LONG lo = 0;
LONG hi = num - 1;
LONG mid;
size_t half;
if (!num || key > base[hi]) {
return -1;
}
while (lo != hi) {
if (num == 2) {
if (key < base[lo]) {
return lo;
}
return hi;
}
half = num / 2;
mid = lo + ((num & 1) ? half : (half - 1));
if (key == base[mid]) {
return mid;
} else if (key < base[mid]) {
hi = mid;
num = ((num & 1) ? (half + 1) : half);
} else {
lo = mid + 1;
num = half + 1;
}
}
return lo;
}
It should search for an element in an array and, if it can't find it, return
the next element.
key is what you are searching, in a *base array of LONG with num elements.
After some tests it seems to work well (the original version was filled with
ASSERTs)
(I will use this function in a bigger look-for-or-insert function)
Some notes:
The function returns the index of the element.
2, 2, 2, 3. Search for 2, it will return the second one (index = 1)
1, 2, 2, 4. Search for 2, it will return the first one (index = 1)
But it should always return the first bigger-than-key element, if it can't
find key (this is very important. I have to insert a new element in that
place, and I want the array to be still ordered after the insertion)
If key > max(all-the-elements) then the function returns -1;
int FindGreaterOrEqual(LONG key, LONG *base, size_t num)
{
LONG lo = 0;
LONG hi = num - 1;
LONG mid;
size_t half;
if (!num || key > base[hi]) {
return -1;
}
while (lo != hi) {
if (num == 2) {
if (key < base[lo]) {
return lo;
}
return hi;
}
half = num / 2;
mid = lo + ((num & 1) ? half : (half - 1));
if (key == base[mid]) {
return mid;
} else if (key < base[mid]) {
hi = mid;
num = ((num & 1) ? (half + 1) : half);
} else {
lo = mid + 1;
num = half + 1;
}
}
return lo;
}