二、算法——06、快速排序(lua实现)

2020-10-22  本文已影响0人  GameObjectLgy
-----快速排序---
local function QuickSort(t, lowIndex, hightIndex)
    if lowIndex >= hightIndex then
        return
    end

    local low = lowIndex
    local hight = hightIndex
    local base = t[low]
    
    while low < hight do
        --从右往左找小于base的数
        while t[hight] >= base and low < hight do
            hight = hight - 1
        end
        t[low] = t[hight]

        --从左往右找大于base的数
        while t[low] < base and low < hight do
            low = low + 1
        end
        t[hight] = t[low ]
    end
    t[low] = base
    QuickSort(t, lowIndex, low)
    QuickSort(t, low+1, hightIndex)
end
-----QuickSort test--------
local t = {5,1,3,6,3,4,2,3}
print("---before QuickSort sort---")
print(table.concat(t,' '))
print("---after QuickSort sort---")
QuickSort(t, 1, 8)
print(table.concat(t,' '))
上一篇 下一篇

猜你喜欢

热点阅读