参考 :http://blog.youkuaiyun.com/hguisu/article/details/7776068
--[[1)选择一个基准元素,通常选择第一个元素或者最后一个元素,
2)通过一趟排序讲待排序的记录分割成独立的两部分,其中一部分记录的元素值均比基准元素值小。另一部分记录的 元素值比基准值大。
3)此时基准元素在其排好序后的正确位置
4)然后分别对这两部分记录用同样的方法继续进行排序,直到整个序列有序。--]]
function swap(i1,i2,arr)
local tmp = arr[i2]
arr[i2] = arr[i1]
arr[i1] = tmp
end
function partition(arr,low,high)
local privotKey
privotKey = arr[low]
while(low < high)do
--从表的两端交替地向中间扫描,
--从high 所指位置向前搜索 --将比基准元素小的交换到低端
while(low < high and arr[high] >= privotKey) do
high = high - 1
end
swap(low,high,arr)
--从low 所指位置向后搜索
while(low < high and arr[low] <= privotKey ) do
low = low + 1
end
swap(low, high,arr)
end
return low
end
function quickSort(arr,low,high)
if low < high then
local privotLoc = partition(arr,low,high); --将表一分为二
quickSort(arr,low,privotLoc -1); --递归对低子表递归排序
quickSort(arr,privotLoc + 1, high); --递归对高子表递归排序
end
end
arr = {3,3,3,3,3,9,8,7,6,5,4}
quickSort(arr,1,#arr)
print(table.concat(arr,","))