From 49595be3ac35960ae9797d7818118cccf656649e Mon Sep 17 00:00:00 2001 From: Lars Mueller Date: Fri, 30 Sep 2022 12:48:59 +0200 Subject: [PATCH] Deprecate comparators in favor of less than funcs; switch binary search return values to `nil, insertion index` if the value is not found --- table.lua | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/table.lua b/table.lua index c4d98ab..56c8926 100644 --- a/table.lua +++ b/table.lua @@ -672,6 +672,7 @@ function max(table) return best_value(table, function(value, other_value) return value > other_value end) end +--! deprecated function default_comparator(value, other_value) if value == other_value then return 0 @@ -682,6 +683,7 @@ function default_comparator(value, other_value) return -1 end +--! deprecated, use `binary_search(list, value, less_than)` instead --> index if element found --> -index for insertion if not found function binary_search_comparator(comparator) @@ -703,12 +705,32 @@ function binary_search_comparator(comparator) end end -binary_search = binary_search_comparator(default_comparator) +function binary_search( + list -- sorted list + , value -- value to be be searched for + , less_than -- function(a, b) return a < b end +) + less_than = less_than or function(a, b) return a < b end + local min, max = 1, #list + while min <= max do + local mid = math.floor((min + max) / 2) + local element = list[mid] + if less_than(value, element) then + max = mid - 1 + elseif less_than(element, value) then + min = mid + 1 + else -- neither smaller nor larger => must be equal + return mid -- index if found + end + end + return nil, min -- nil, insertion index if not found +end --> whether the list is sorted in ascending order -function is_sorted(list, comparator) +function is_sorted(list, less_than --[[function(a, b) return a < b end]]) + less_than = less_than or function(a, b) return a < b end for index = 2, #list do - if comparator(list[index - 1], list[index]) >= 0 then + if less_than(list[index], list[index - 1]) then return false end end