Skip to content

Instantly share code, notes, and snippets.

@rangercyh
Last active December 18, 2015 17:39
Show Gist options
  • Save rangercyh/5819839 to your computer and use it in GitHub Desktop.
Save rangercyh/5819839 to your computer and use it in GitHub Desktop.
a stable sort algorithm on mutil condition array
--[[
稳定的多维条件数组排序
由调用者保证tbCondition的元素个数大于等于维度nDimension
]]
function MutilArraySort(tbCondition, nDimension)
local tbResult = {}
for i = 1, #tbCondition do
local nInsert = 0
local nLocal = 1
for k = 1, nDimension do
local function DimensionCompare(j)
if j > #tbResult then
return #tbCondition + 1
end
if tbCondition[i][k] > tbCondition[tbResult[j]][k] then
return j
elseif tbCondition[i][k] == tbCondition[tbResult[j]][k] then
return 0, j
else
return DimensionCompare(j + 1)
end
end
nInsert, nLocal = DimensionCompare(nLocal)
if nInsert > 0 and nInsert <= #tbResult then
table.insert(tbResult, nInsert, i)
break
elseif nInsert > #tbResult then
table.insert(tbResult, i)
break
end
if k == nDimension then
table.insert(tbResult, i)
break
end
end
end
return tbResult
end
tbCondition = {
[1] = { 1, 2, 6, 6 },
[2] = { 5, 2, 8, 5 },
[3] = { 5, 2, 7, 6 },
[4] = { 5, 2, 1, 4 },
}
local tbResult = MutilArraySort(tbCondition, 4)
for i = 1, #tbResult do
print(tbResult[i])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment