diff options
author | William McPherson <willmcpherson2@gmail.com> | 2019-11-29 17:22:06 +1100 |
---|---|---|
committer | Andreas Kling <awesomekling@gmail.com> | 2019-11-29 11:04:01 +0100 |
commit | 680fd3999efc9caa1698304e157cbef1308b48df (patch) | |
tree | d55080ece0f00b195c41232c8aac1fcb2151f9ac /Libraries/LibC | |
parent | 4ef6be82123ef7c1788db4725ad9f3c0d5a86746 (diff) | |
download | serenity-680fd3999efc9caa1698304e157cbef1308b48df.zip |
LibC: Implement bsearch
Nothing fancy, just a simple implementation of bsearch(3).
Diffstat (limited to 'Libraries/LibC')
-rw-r--r-- | Libraries/LibC/stdlib.cpp | 17 |
1 files changed, 15 insertions, 2 deletions
diff --git a/Libraries/LibC/stdlib.cpp b/Libraries/LibC/stdlib.cpp index d0dc63e9fb..4a5f23fe6c 100644 --- a/Libraries/LibC/stdlib.cpp +++ b/Libraries/LibC/stdlib.cpp @@ -509,8 +509,21 @@ char* mkdtemp(char* pattern) void* bsearch(const void* key, const void* base, size_t nmemb, size_t size, int (*compar)(const void*, const void*)) { - dbgprintf("FIXME(LibC): bsearch(%p, %p, %u, %u, %p)\n", key, base, nmemb, size, compar); - ASSERT_NOT_REACHED(); + int low = 0; + int high = nmemb - 1; + while (low <= high) { + int middle = (low + high) / 2; + void* middle_memb = const_cast<char*>((const char*)base + middle * size); + int comparison = compar(key, middle_memb); + if (comparison < 0) + high = middle - 1; + else if (comparison > 0) + low = middle + 1; + else + return middle_memb; + } + + return NULL; } div_t div(int numerator, int denominator) |