Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- struct BSearchResult {
- size_t low;
- size_t high;
- int result;
- };
- struct BSearchResult
- bsearch2(const void *key, const void *base, size_t nmemb, size_t size,
- int (*compar)(const void *p1, const void *p2, void *user),
- void *user) {
- size_t low = 0, high = nmemb - 1, mid;
- struct BSearchResult res;
- if (nmemb == 0) {
- res.result = 0;
- res.low = 0;
- res.high = 0;
- return res;
- }
- while (low <= high) {
- mid = low + (high - low) / 2;
- if (compar(key, base + size * mid, user) == 0) {
- res.low = mid;
- while (res.low != -1 &&
- compar(key, base + size * res.low, user) == 0) {
- res.low--;
- }
- res.low++;
- res.high = mid;
- while (res.high != nmemb &&
- compar(key, base + size * res.high, user) == 0) {
- res.high++;
- }
- res.result = 1;
- return res;
- } else if (compar(key, base + size * mid, user) > 0) {
- low = mid + 1;
- } else {
- if (mid == 0) {
- low = 0;
- break;
- }
- high = mid - 1;
- }
- }
- res.result = 0;
- res.low = low;
- res.high = low;
- return res;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement