File: bsearch.c

package info (click to toggle)
cc65 2.19-2
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 20,268 kB
  • sloc: ansic: 117,151; asm: 66,339; pascal: 4,248; makefile: 1,009; perl: 607
file content (50 lines) | stat: -rw-r--r-- 1,163 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
** bsearch.c
**
** 1998-06-17, Ullrich von Bassewitz
** 2015-06-21, Greg King
*/



#include <stdlib.h>



void* __fastcall__ bsearch (const void* key, const void* base, size_t n,
                            size_t size, int __fastcall__ (* cmp) (const void*, const void*))
{
    int current;
    int result;
    int found = 0;
    int first = 0;
    int last = n - 1;

    /* Binary search */
    while (first <= last) {

        /* Set current to mid of range */
        current = (last + first) / 2;

        /* Do a compare */
        result = cmp ((void*) (((int) base) + current*size), key);
        if (result < 0) {
            first = current + 1;
        } else {
            last = current - 1;
            if (result == 0) {
                /* Found one entry that matches the search key. However there may be
                ** more than one entry with the same key value and ANSI guarantees
                ** that we return the first of a row of items with the same key.
                */
                found = 1;
            }
        }
    }

    /* Did we find the entry? */
    return (void*) (found? ((int) base) + first*size : 0);
}