--冒泡法排序,强调冒泡,两两比较,大的逐步往后冒
local arr = {3,11,5,2,6,1,7,4,6,9,3}
local function bubbleSort(tab)
for i = 1 ,#tab -1 do
for j = 1, #tab - i do
if tab[j] > tab[j+1] then
tab[j] ,tab[j+1] = tab[j+1] ,tab[j]
end
end
end
end
bubbleSort(arr)
for i = 1 ,#arr do
print(arr[i])
end
--快排算法
1.找一个基准数字,把它记录下来,并且当前位置理解为一个坑,
2.从最右侧找一个比它小的数字填这个坑,找到的那个位置又变成了新坑,
3.再从左往右找一个比基准数字大的,再去填新坑。
4.找完之后,最后一个坑用基准数字填。这样,基准数字左侧的数字都比它小,右侧的都比它大。
5.基准数字左侧的和右侧的分别递归排序,排完就OK了。
local arr = {3,11,5,2,6,1,7,4,6,9,3}
local function quickSort(tab,left,right)
local i = left
local j = right
local x = tab[i] --每次执行快排的基准数字
if i < j then
while(i < j)
do
for m = j,i,-1 do
j = m
if tab[m] < x then
tab[i] = tab[m] --填坑
break
end
end
for n = i,j do
i = n
if tab[n] > x then
tab[j] = tab[n] --填坑
break
end
end
end
tab[i] = x -- i == j
quickSort(tab,left,i-1)
quickSort(tab,i+1,right)
end
end
quickSort(arr,1,#arr)
for i = 1 ,#arr do
print(arr[i])
end
--插入排序
--从第一个元素开始,该元素可以认为已经排好序,取下一个,
-- 在已经排好序的序列中向前扫描,有元素大于这个新元素,
-- 将已经在排好序中的元素移到下一个位置,依次执行
local arr = {3,0,5,2,6,1,7,4,6,9,3}
local function inserSort(tab)
for i = 2 ,#tab do --从前往后遍历
local number = tab[i]
for j = i-1,1,-1 do --从已排序里面,倒序遍历
if tab[j] then
if number <= tab[j] then
tab[j+1] = tab[j]
tab[j] = number
else
break
end
end
end
end
end
inserSort(arr)
for i = 1 ,#arr do
print(arr[i])
end
--希尔排序
--间隔gap加插入排序,间隔越来越小,到最后当间隔为1时就排好了
local socket = require("socket")
print(socket.gettime())
local arr = {3,0,5,2,6,1,7,4,6,9,3}
local function shellSort(tab)
local len = #tab
local temp
local gap = math.floor(len / 2)
while(gap > 0) --希尔排序
do
for i = gap, len do --插入排序
temp = tab[i]
local preIndex = i - gap
while(preIndex >= 1 and tab[preIndex] > temp)
do
tab[preIndex + gap] = tab[preIndex]
preIndex = preIndex - gap
end
tab[preIndex + gap] = temp
end
gap = math.floor(gap/2)
end
return tab
end
local result = shellSort(arr)
for i = 1 ,#result do
print(result[i])
end