You can sort a list of things using table.sort
:
1 | local list = { 5 , 3 , 1 , 2 , 4 } |
3 | print (list [ 1 ] , list [ 2 ] , list [ 3 ] , list [ 4 ] , list [ 5 ] ) |
This sorts by comparing elements using <
. You can't compare parts using this, of course. That's why table.sort
has an optional second parameter which is your own function to replace <
:
1 | function shorter(left, right) |
2 | return left.Size.y < right.Size.y |
4 | table.sort(parts, shorter) |
That will do what you want if parts
is a list of parts.
Filtering for only parts
If model
is a model that contains parts and some other objects, it would probably be best to filter the other objects out. You can either do that by constructing a new table:
1 | local children = model:GetChildren() |
3 | for _, child in pairs (children) do |
4 | if child:IsA( "BasePart" ) then |
5 | table.insert(parts, child) |
or by removing non-part elements from the list:
1 | local parts = model:GetChildren() |
2 | for i = #parts, 1 , - 1 do |
5 | if not child:IsA( "BasePart" ) then |
Implementing Sorting
It looks like you were trying to implement a sort yourself. In general, this is a bad idea, because it's going to be more confusing and slower than the built-in implementation. Still, it's a interesting problem that is taught in intro CS.
Here's a few ways to sort things, but just using <
to compare (replace a < b
with less(a, b)
for custom comparisons)
Selection Sort
IDEA: First thing is smallest. Second thing is smallest (other than the smallest one). Third thing is smallest (other than the 2 smallest). Etc.
Performance: Very slow, always.
Copying implementation
01 | local list = { 5 , 3 , 1 , 2 , 4 } |
06 | if list [ i ] < list [ mini ] then |
10 | table.insert(sorted, table.remove(list, mini)) |
In place implementation (Less memory, faster)
4 | if list [ j ] < list [ minj ] then |
8 | list [ i ] , list [ minj ] = list [ minj ] , list [ i ] |
Bubble Sort
IDEA: Move bigger things up one step at a time.
Performance: Very slow, almost always. Sometimes very fast. No extra memory usage.
TODO
Merge Sort
IDEA: Be stupid, and unable to sort lists of more than 2 elements (which we can do because of <
). Sort pieces of lists and put them together.
Performance: Fast, always. Requires a lot of extra memory.
Quicksort
IDEA: Pick an element. All the elements less than it can be sorted in their own pile. All the element more than it can be sorted in their own pile.
Performance: Fast, but only usually. No extra memory usage (needed).
Copying implementation -- wastes memory
01 | function quicksort(list) |
13 | elseif el > pivot then |
14 | table.insert(more, el) |
16 | table.insert(same, el) |
20 | less = quicksort(less) |
22 | table.insert(sorted, less [ i ] ) |
25 | table.insert(soted, same [ i ] ) |
27 | more = quicksort(more) |
29 | table.insert(sorted, more [ i ] ) |