示例#1
0
/** @memo   Binary search of an already sorted array.

    @doc    Binary search using the comparison function supplied 
    'compfunc'. The comparison function must return:<br>
    <pre>    
		<0  If node1 is less than node2.
		0   If node1 is equivalent to node2.
		>0  If node1 is greater than to node2.
	</pre>
             
    @return Pointer to the found node within the array,
    0 if not found or error.
 */
void * rtp_bsearch (
  const void *obj,                      /** Object that is to be found. */
  const void *head,                     /** Head of array to search. */
  unsigned int num,                     /** Number of nodes in array. */
  unsigned int size,                    /** Size of each node. */
  RTP_BSEARCH_COMPARISON_FN compfunc    /** Comparison function. */
  )
{
long curRightPos = num - 1;
long curLeftPos  = 0;
long medianIndex = 0;
int  result      = 0;

    while (curLeftPos <= curRightPos)
    {
        medianIndex = (curRightPos + curLeftPos) / 2;
        result = compfunc ((const void *) (((long)head) + (medianIndex * size)), obj);
        
        if (result < 0)
        {
            curLeftPos = medianIndex + 1;
        }
        else if (result > 0)
        {
            curRightPos = medianIndex - 1;
        }
        else
        {
            return ((void *) (((long)head) + (medianIndex * size)));
        }
    }
    return (0);
}
示例#2
0
文件: compfunc.c 项目: rjcostales/c
int main(int argc, char *argv[])
{
	ptr2func pwr4;
	ptr2func pwr6;
	ptr2func pwr9;

	pwr4 = compfunc(&pwr2, &pwr2);
	printf("%8.1f\n", pwr4(2.0));
	printf("%8.1f\n", pwr4(3.0));

	pwr6 = compfunc(&pwr2, &pwr3);
	printf("%8.1f\n", pwr6(2.0));
	printf("%8.1f\n", pwr6(3.0));

	pwr9 = compfunc(&pwr3, &pwr3);
	printf("%8.1f\n", pwr9(2.0));
	printf("%8.1f\n", pwr9(3.0));
}