本文主要是介绍lua一些排序,后续继续添加,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
目录
- 冒泡排序
- 简单选择排序
冒泡排序
--- 打印table
function printTB(tb)print("打印tb", table.concat( tb, ", "))
end
--- 冒泡排序
local tbArray = {3,5,7,34,1,78,77,23,-10,33,73,2345,45}function buddle_sort(tbArray)local i,j,tmpfor i=1,#tbArray-1,1 dofor j=1,#tbArray-i,1 do -- tbArray-i的原因是, j+1位的值已经是最终结果,不需要再变动print("+++j 当前比较的数="..tbArray[j].." "..tbArray[j+1])if tbArray[j] < tbArray[j+1] thenprint("交换".. tbArray[j].." ".. tbArray[j+1])tmp = tbArray[j+1]tbArray[j+1] = tbArray[j]tbArray[j] = tmpendendprintTB(tbArray)end
endbuddle_sort(tbArray)
简单选择排序
--- 打印table
function printTB(tb)print("打印tb", table.concat( tb, ", "))
end
--- 简单选择排序
local tbArray = {3,5,7,34,1,78,77,23,-10,33,73,2345,45}function select_sort( tb )local i,j,max,tmpfor i = 1 , #tb-1, 1 domax = ifor j = i+1, #tb, 1 doif tb[j] > tb[max] then-- 找出最大的一个值所在的下标max = jendendif max ~= i thentmp = tbArray[max]tbArray[max] = tbArray[i]tbArray[i] = tmpendprintTB(tb)end
endselect_sort(tbArray)
这篇关于lua一些排序,后续继续添加的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!