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