local quick_sort = Future:new() function quick_sort:sort(A, lo, hi, i) if lo >= 0 and lo < hi then lt, gt = partition(A, lo, hi) -- Multiple return values if #self.state["lt"] >= i and #self.state["gt"] >= i then self:sort(A, lo, self.state["lt"][i] - 1, i+1) self:sort(A, self.state["gt"][i] + 1, hi, i+1) else table.insert(self.state["lt"], lt) table.insert(self.state["gt"], gt) return false end end return true end function quick_sort:poll(array) return self:sort(array, 0, array:size(),0) end -- Divides array into three partitions function partition(A, lo, hi) -- Pivot value local pivot = A.at((lo + hi) / 2) -- Choose the middle element as the pivot (integer division) -- Lesser, equal and greater index local lt = lo local eq = lo local gt = hi -- Iterate and compare all elements with the pivot while eq <= gt do if A[eq] < pivot then -- Swap the elements at the equal and lesser indices A:swap(eq, lt) -- Increase lesser index lt = lt + 1 -- Increase equal index eq = eq + 1 elseif A[eq] > pivot then -- Swap the elements at the equal and greater indices A:swap(eq, gt) -- Decrease greater index gt = gt - 1 else -- if A[eq] = pivot then -- Increase equal index eq = eq + 1 end end -- Return lesser and greater indices return lt, gt end function make_available(sorter_list) table.insert(sorter_list, "quick_sort") end