0
点赞
收藏
分享

微信扫一扫

用lua实现排序算法

冒泡排序

function bubblesort(t)
for i=1, #t-1 do
for j=i+1, #t do
if (t[i]>t[j]) then
t[i],t[j] = t[j],t[i]
end
end
end
return t
end

arr = {3,1,7,2,9,8}
beforesort = table.concat(arr, "-")
print(beforesort)
print("---------------------------")
newarr = bubblesort(arr)
aftersort = table.concat(newarr, "-")
print(aftersort)

用lua实现排序算法_lua


选择排序

重复的代码省略

function selectsort(t)
for i=1, #t-1 do
minindex = i
for j=i+1, #t do
if t[j] < t[minindex] then
minindex = j
end
end
t[i],t[minindex] = t[minindex],t[i]
end
return t
end

用lua实现排序算法_lua_02

插入排序

function insertsort(t)
for i=1, #t-1 do
currentvalue = t[i+1]
insertindex = i
while insertindex > 0 and currentvalue < t[insertindex] do
t[insertindex+1] = t[insertindex]--将大于插入值的对象往后挪一个
insertindex = insertindex-1
end
t[insertindex+1] = currentvalue
end
return t
end

用lua实现排序算法_插入排序_03

希尔排序

function shellsort(t)   
step = #t//2
while step >=1 do
for j=step+1, #t do
temp = t[j]
for i= j-step, 1, -step do
if t[i] >temp then
t[i+step] =t[i]
t[i] = temp
end
end
end
step = step//2
end
return t
end

快速排序

function partition(t, left, right)
pivot = t[left]
while left < right do
while left < right and t[right] >= pivot do
right = right-1
end
t[left] = t[right]
while left < right and t[left]<= pivot do
left = left+1
end
t[right] = t[left]
end
t[left] = pivot
return left
end

function quicksort(t, left, right)
if (left <right) then
local pivot = partition(t, left, right)
quicksort(t,left,pivot-1)
quicksort(t,pivot+1,right)
end
return t
end

用lua实现排序算法_lua_04

归并排序-待补充

举报

相关推荐

0 条评论