From c58edfa48616bd8b3b121764f69b19a20473125a Mon Sep 17 00:00:00 2001 From: Lorenzo Cogotti Date: Thu, 1 Jun 2023 22:43:25 +0200 Subject: [PATCH] [algo] Optimize insertion sort. --- algo.lua | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/algo.lua b/algo.lua index ceac113..898bf8f 100644 --- a/algo.lua +++ b/algo.lua @@ -34,6 +34,24 @@ end local function lt(a, b) return a < b end +local function _insertionsort(array, lo, hi, less) + for i = lo+1,hi do + local k = lo + local v = array[i] + + for j = i,lo+1,-1 do + local el = array[j-1] + if less(v, el) then + array[j] = el + else + k = j + break + end + end + array[k] = v + end +end + --- Sort array using Insertion Sort - O(n^2). -- -- Provides the most basic sorting algorithm around. @@ -46,19 +64,7 @@ local function lt(a, b) return a < b end -- less than its second argument, -- false otherwise. function algo.insertionsort(array, less) - less = less or lt - - for i = 2,#array do - local val = array[i] - local j = i - - while j > 1 and less(val, array[j-1]) do - array[j] = array[j-1] - j = j - 1 - end - - array[j] = val - end + _insertionsort(array, 1, #array, less or lt) end --- Binary search last element where