Re: How to sort data (when table.sort cannot be used)?
Posted: Thu Oct 31, 2024 7:39 pm
Thanks! I will look into it.
By the way, if someone needs a code for quicksort :
Usage :
By the way, if someone needs a code for quicksort :
Code: Select all
-- https://en.wikipedia.org/wiki/Quicksort
local function swap(db, i, j) -- swap in all fields
for f=1, #db do
db[f][i], db[f][j] = db[f][j], db[f][i]
end
end
local function partition(db, field, left, right)
local pivotValue = db[field][right]
local i = left - 1
for j = left, right - 1 do
if db[field][j] <= pivotValue then
i = i + 1
swap(db, i, j)
end
end
swap(db, i + 1, right)
return i + 1
end
local pivotIndex
local function quicksort(db, field, left, right)
if left < right then
pivotIndex = partition(db, field, left, right)
quicksort(db, field, left, pivotIndex - 1)
quicksort(db, field, pivotIndex + 1, right)
end
end
return quicksort
Code: Select all
local quicksort = require "quicksort"
quicksort(db, 2, 1, #db.name)
quicksort(db, "age", 1, #db.name)