Lua实现快速排序
// 快排
arr = {3,2,5,1,5,8,6,3,15,341,8,3,54,84,165,416,8541,145}
n = #arr
function QuickSort(arr,left,right)
if(left < right) then
center =Partition(arr,left,right)
QuickSort(arr,left,center-1)
QuickSort(arr,center+1,right)
end
end
function Partition(arr,left,right)
i=left
j=right
pivot = arr[left]
while(true) do
while(i < j and arr[i] <= pivot) do
i = i + 1
end
while(j >= i and arr[j]>pivot) do
j=j-1
end
if i>=j then
break
end
temp = arr[i]
arr[i] =arr[j]
arr[j] =temp
end
arr[left] = arr[j]
arr[j] = pivot
return j
end
QuickSort(arr,1,n)
for k,v in pairs(arr) do
print(v)
end
输出结果: