冒泡排序的基本思想就是:从无序序列头部开始,进行两两比较,根据大小交换位置,直到最后将最大(小)的数据元素交换到了无序队列的队尾,从而成为有序序列的一部分;下一次继续这个过程,直到所有数据元素都排好序。
算法的核心在于每次通过两两比较交换位置,选出剩余无序序列里最大(小)的数据元素放到队尾
冒泡排序的平均时间复杂度为O(n^2)。
local printT = function(t)
print("printT ---------------")
table.walk(t, function(v, k)
print(k, v)
end)
print("---------------")
end
function table.orderByBubbling(t)
for i = 1, #t do
for j = #t, i + 1, -1 do
if t[j - 1] > t[j] then
swap(t, j, j - 1)
--printT(t)
end
end
end
return t
end
function swap(list,low,high)
local temp = 0
temp = list[low]
list[low] = list[high]
list[high] = temp
end
function table.walk( t, fn )
for k, v in pairs( t ) do
fn( v, k )
end
end
local test_list = {1,2,-2,3,-3444,-3344,3334,334,344,345,667,77}
local num = #test_list
table.orderByBubbling(test_list) -- 总结
print("after order--------")
printT(test_list)