/****************************************************************************/
/*	Copyright (c) 2009, Bendor Research Pty. Ltd. All rights reserved.		*/
/*	This software is released under the GNU General Public License, version	*/
/*	3, with the exemptions that 1) the header files installed by this 	 	*/
/*	package can be included in closed-source code and 2) the libraries		*/
/*	built by this package can be statically linked into a closed-source 	*/
/*	binary. See the file LICENSE for the details.							*/
/*	This software is provided "AS IS", without any warranty or guarantee.	*/
/*	By using this software you acknowledge that neither Bendor Research nor	*/
/*	any of its personnel or affiliates can be held liable for any damages,	*/
/*	including, but not limited to, loss of business, loss of money, loss of */
/*	life, loss of reputation, arising out of this software being faulty or	*/
/*	not performing as advertised, even if Bendor Research was aware of such	*/
/*	faults in the software. You use this software at your own risk, any and */
/*	all liabilities that arise out of your using this software are strictly	*/
/*	yours.																	*/
/****************************************************************************/

#include <stdlib.h>

/** @addtogroup stdlib */
/**	@{ */

/**
*	Binary search in an ordered array.
*
*	The routine searches for a key in an array of identical but otherwise
*	arbitrary comparable objects that are sorted in ascending order. As
*	the name implies, the routine uses binary search, therefore the maximum
*	number of compares is ceil( log2( \p nmemb ) ).
*
*	@param	key		Pointer to the key that should be found in the array.
*
*	@param	base	Pointer to the array of objects to search. The array
*					must be sorted in ascending order.
*
*	@param	nmemb	The number of objects in the array.
*
*	@param	size	The size of each member of the array, as returned by the
*					\p sizeof operator.
*
*	@param	comp	A pointer to a function that receives a pointer to the key
*					as its first parameter and a pointer to an object as its
*					second parameter. The function then returns less than 0,
*					0 or greater than 0 if the key is less than, equal to or
*					greater than the object, respectively.
*
*	@return			If the given key is found in the array, then the return
*					value is a pointer to that object. If the key is not found,
*					then NULL is returned. If the array contains multiple
*					objects with the given search key, then which one is
*					returned is undetermined.
*/

void	*bsearch( const void *key, const void *base, size_t nmemb, size_t size,
				  int (*comp)( const void *, const void * ) )
{
size_t	beg, end, mid;
int		tst;
void	*ptr;

	beg = 0;
	end = nmemb - 1;

	while ( beg <= end ) {

		mid = ( beg + end ) / 2;
		ptr = (char *) base + mid * size;
		tst = (*comp)( key, ptr );

		if ( ! tst ) return( ptr );

		if ( tst < 0 )

			end = mid - 1;
		else
			beg = mid + 1;
	}

	return( NULL );
}

/** @} */

