Sorted magnitude table

I have a iterator that gets the magnitudes of various minor points from a centralized major point.
I currently just insert these into a table. But I want them to be ordered by their values least to greatest.

I know I can find a way with sort, but I was wondering if I even have to do this; is there a way I can instead automatically put them in the table in a way that would just be already sorted as intended at insertion time?

You would need a module that would automatically sort them, it wont automatic sort in any other way.

You can only use table.sort if your table is an array. Otherwise you will have to use a loop to go through all of the tables contents to sort them into a new table. I wouldn’t recommend overcomplicating anything.

A binary searchtree might be what you are looking for:

You can also pass a custom sort function into table.sort.
Assuming your array values are Vector3s:

local center = (center point)
local points = {(other points)}

-- A custom sort function is made to return true when element A comes before element B in the array.
local function distanceSort(a, b)
	return (a - center).Magnitude < (b - center).Magnitude
end

table.sort(points, distanceSort)

I think you can do this:

for i, Point in pairs(Points) do
    for i, TablePoint in pairs(Table) do
        if Point >= TablePoint then
            table.insert(Point, Table, i)
        end
    end
end

Something like that.

Basically it loops through the points and inserts them in the index of the table where it is greater than/

Thank you everyone, constructive and insightful takes! I ended up just using a custom sort pred function that takes the two as array values and compares their first index value, which stores the magnitude.

1 Like