--------------------------------------------------------------
function quicksort_recursive(data,left,right,func)
local next = compare(data,left,right,func);
if next ~= nil then
quicksort(data,left,next-1,func);
quicksort(data,next + 1,right,func);
end
end
function quicksort_stack(data,left,right,func)
local stack={}
local index = compare(data,left,right,func);
table.insert(stack,{index,left,right})
local count = #(stack)
while count > 0 do
local keyindex = stack[1][1]
local keyleft = stack[1][2]
local keyright = stack[1][3]
local indexleft = compare(data,keyleft,keyindex-1,func);
if indexleft ~=nil and indexleft < keyindex then
table.insert(stack,{indexleft,keyleft,keyindex-1})
end
local indexright = compare(data,keyindex + 1,keyright,func);
if indexright ~=nil and indexright > keyindex then
table.insert(stack,{indexright,keyindex + 1,keyright})
end
table.remove(stack,1)
count = #(stack)
end
stack = nil
end
function compare(data,left,right,func)
if left >= right then
return nil
end
local key = data[left]
local i = left;
local j = right;
while i < j do
while j > left and i < j do
if func(data[j],key) then--<
data[i] = data[j]
break;
end
j = j - 1
end
while i < right and i < j do
if func(key,data[i]) then--<
data[j] = data[i]
break;
end
i = i + 1
end
data[i] = key
end
return i
end
function sortfun(a,b)
return (a > b)
end
----------------------------------------------------------------
local data = {0,23,41,52,63,44,25,96,17,8,435,565,99,12,34}
for _,value in pairs(data) do
print(value)
end
quicksort_stack(data,1,#(data),sortfun)
for _,value in pairs(data) do
print(value)
end
io.read()
快速排序lua实现 递归和栈两种实现
最新推荐文章于 2024-06-06 14:29:19 发布