binary search for strings

This commit is contained in:
Nikita Smith
2025-09-07 19:36:47 -07:00
committed by Ryan Fleury
parent 00536f7ea8
commit 7193986305
2 changed files with 33 additions and 0 deletions
+32
View File
@@ -21,3 +21,35 @@ str8_list_pop_front(String8List *list)
return node;
}
internal U64
str8_array_bsearch(String8Array arr, String8 value)
{
if (arr.count > 1) {
int lo_compar = str8_compar_case_sensitive(&value, &arr.v[0]);
if (lo_compar == 0) {
return 0;
}
int hi_compar = str8_compar_case_sensitive(&value, &arr.v[arr.count-1]);
if (hi_compar == 0){
return arr.count-1;
}
if (lo_compar > 0 && hi_compar < 0) {
for (U64 l = 0, r = arr.count -1; l <= r; ) {
U64 m = l + (r- l) / 2;
int cmp = str8_compar_case_sensitive(&arr.v[m], &value);
if (cmp == 0) {
return m;
} else if (cmp < 0) {
l = m + 1;
} else {
r = m - 1;
}
}
}
} else if (arr.count == 1 && str8_match(arr.v[0], value, 0)) {
return 0;
}
return max_U64;
}
+1
View File
@@ -8,3 +8,4 @@ internal String8Node * str8_list_pop_front(String8List *list);
internal B32 str8_starts_with(String8 string, String8 expected_prefix);
internal U64 str8_array_bsearch(String8Array arr, String8 value);