Lua的排序算法——快速排序


a = {1,3,5,2,6,8,10,3,6,20}

--快速排序(以数组最左边的值为基准,比它小的放左边,比它大的放右边,然后再对左右两边的数组进行同样的操作,直到细分排列完成)
local function KuaiSuPaiXu(arr, startIndex, endIndex)
	if startIndex >= endIndex then
		return
	end
	local lowIndex = startIndex
	local highIndex = endIndex
	local key = arr[lowIndex]
	while(lowIndex < highIndex) do
		while(arr[highIndex] >= key and highIndex > lowIndex) do --找到一个小于key的值放在左边
			highIndex = highIndex - 1
		end
		arr[lowIndex] = arr[highIndex]
		while(arr[lowIndex] <= key and highIndex > lowIndex) do --找到一个大于Key的放在右边
			lowIndex = lowIndex + 1
		end
		arr[highIndex] = arr[lowIndex]
		arr[lowIndex] = key --把key放在游标停止处
	end
	--对数组整体做一次排序,得到中间索引,切分成左右两个数组,然后再递归
	KuaiSuPaiXu(arr, startIndex, lowIndex - 1)
	KuaiSuPaiXu(arr, lowIndex + 1, endIndex)
end

local function PrintTab(t)
	for k, v in pairs(t) do
		print(v)
	end
end

print("KuaiSuPaiXu")
KuaiSuPaiXu(a, 1, #a)
PrintTab(a)

 

快速排序是一种高效的排序算法,它的基本思想是通过一次排序数组分成两个子数组,其中一个子数组的所有元素都比另一个子数组的所有元素小,然后再分别对这两个子数组递归地进行快速排序。 以下是使用Lua语言实现快速排序的示例代码: ``` function quickSort(arr, left, right) left = left or 1 right = right or #arr if left >= right then return end local pivotIndex = partition(arr, left, right) quickSort(arr, left, pivotIndex - 1) quickSort(arr, pivotIndex + 1, right) end function partition(arr, left, right) local pivot = arr[right] local i = left - 1 for j = left, right - 1 do if arr[j] < pivot then i = i + 1 arr[i], arr[j] = arr[j], arr[i] end end arr[i + 1], arr[right] = arr[right], arr[i + 1] return i + 1 end -- 测试 local arr = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5} quickSort(arr) for i, v in ipairs(arr) do print(v) end ``` 在上面的代码中,quickSort函数接收一个数组arr和两个可选参数left和right作为参数,其中left和right分别表示需要排序的子数组的左右边界,如果没有传递这两个参数,默认将整个数组排序。在快速排序中,我们首先通过partition函数将数组分成两个子数组,然后再对这两个子数组递归地进行快速排序。 在partition函数中,我们选择数组中的最后一个元素作为pivot,然后通过一次循环将数组分成两个子数组,其中一个子数组的所有元素都比pivot小,另一个子数组的所有元素都比pivot大。最后,将pivot交换到子数组的中间位置,返回pivot的索引。 在测试代码中,我们使用了一个随机数组进行测试,并打印出排序后的结果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值