Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 15 additions & 24 deletions lua/quicksort.lua
Original file line number Diff line number Diff line change
@@ -1,34 +1,25 @@

function partition(array, left, right, pivotIndex)
local pivotValue = array[pivotIndex]
array[pivotIndex], array[right] = array[right], array[pivotIndex]

local storeIndex = left

for i = left, right-1 do
if array[i] <= pivotValue then
array[i], array[storeIndex] = array[storeIndex], array[i]
storeIndex = storeIndex + 1
local function quicksort(t, left, right)
if right < left then return end
local pivot = left
for i = left + 1, right do
if t[i] <= t[pivot] then
if i == pivot + 1 then
t[pivot],t[pivot+1] = t[pivot+1],t[pivot]
else
t[pivot],t[pivot+1],t[i] = t[i],t[pivot],t[pivot+1]
end
pivot = pivot + 1
end
array[storeIndex], array[right] = array[right], array[storeIndex]
end

return storeIndex
end

function quicksort(array, left, right)
if right > left then
local pivotNewIndex = partition(array, left, right, left)
quicksort(array, left, pivotNewIndex - 1)
quicksort(array, pivotNewIndex + 1, right)
end
quicksort(t, left, pivot - 1)
quicksort(t, pivot + 1, right)
end


array = { 1, 5, 2, 17, 11, 3, 1, 22, 2, 37 }
local array = { 1, 5, 2, 17, 11, 3, 1, 22, 2, 37 }

quicksort(array, 1, #array)

for _, v in pairs(array) do
print(v)
end
end