[Solved]How to sort data (when table.sort cannot be used)?

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
qwdqwqwffqw
Prole
Posts: 33
Joined: Sat Jan 25, 2020 4:11 pm

Re: How to sort data (when table.sort cannot be used)?

Post by qwdqwqwffqw »

Thanks! I will look into it.

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
Usage :

Code: Select all

local quicksort = require "quicksort"
quicksort(db, 2, 1, #db.name)
quicksort(db, "age", 1, #db.name)
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Bing [Bot], Google [Bot] and 4 guests