mirror of
https://github.com/RGBCube/serenity
synced 2025-07-27 23:17:45 +00:00
AK: Add a BinarySearch template implementation
binary_search takes a haystack, a size, a needle and a compare function. The compare function should return negative if a < b, positive if a > b and 0 if a == b. The "sane default" compare function is integral_compare which implements this with subtraction a - b. binary_search returns a pointer to a matching element, NOT necessarily the FIRST matching element. It returns a nullptr if the element was not found. This patch includes tests for binary_search.
This commit is contained in:
parent
f8a0eb616c
commit
d7177212fd
3 changed files with 118 additions and 1 deletions
32
AK/BinarySearch.h
Normal file
32
AK/BinarySearch.h
Normal file
|
@ -0,0 +1,32 @@
|
|||
#pragma once
|
||||
|
||||
namespace AK {
|
||||
|
||||
template<typename T>
|
||||
int integral_compare(const T& a, const T& b)
|
||||
{
|
||||
return a - b;
|
||||
}
|
||||
|
||||
template<typename T, typename Compare>
|
||||
T* binary_search(T* haystack, size_t haystack_size, const T& needle, Compare compare = integral_compare)
|
||||
{
|
||||
int low = 0;
|
||||
int high = haystack_size - 1;
|
||||
while (low <= high) {
|
||||
int middle = (low + high) / 2;
|
||||
int comparison = compare(needle, haystack[middle]);
|
||||
if (comparison < 0)
|
||||
high = middle - 1;
|
||||
else if (comparison > 0)
|
||||
low = middle + 1;
|
||||
else
|
||||
return &haystack[middle];
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
using AK::binary_search;
|
Loading…
Add table
Add a link
Reference in a new issue