快速排序Lua实现

参考 :http://blog.csdn.net/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,","))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

骇客之技术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值