Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C Programming
the arithmetic from k&r seems wrong
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="user923005, post: 3092552"] For the OP... Here is the world's easiest to understand binary search: #include <stdlib.h> void *binsearch( const void *key, const void *bbase, size_t element_count, size_t element_size, int (*comp) (const void *, const void *) ) { const char *base = bbase; size_t window; int cmp; const void *guess; /* Start with a window of the full size and halve it each pass */ for (window = element_count; window != 0; window >>= 1) { /* Examine the middle element of this window */ guess = base + (window >> 1) * element_size; /* by definition, comp returns -1 for <, 0 for =, +1 for > */ cmp = comp(key, guess); if (!cmp) /* Did we find it? */ return ((void *) guess); if (cmp > 0) { /* It's in the other half... */ base = (char *) guess + element_size; window--; } } return (NULL); } [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C Programming
the arithmetic from k&r seems wrong
Top