🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Sorting elements in parent->child order

Started by
13 comments, last by alvaro 3 years, 7 months ago

If this is something that's super important and you don't mind adding a bit of space to your objects, just add a depth ID. When an object goes into the tree, it gets it's parent's depth + 1. Then you can simply sort on that.

Advertisement

Gnollrunner said:
If this is something that's super important and you don't mind adding a bit of space to your objects, just add a depth ID. When an object goes into the tree, it gets it's parent's depth + 1. Then then you can simply sort on that.

Yeah, thats why I basically ended up doing. The objects are already big af, they are only used to represent the asset/editor-side of my visual scripting, there is a separate runtime-representation being compiled which is more efficent.

Gnollrunner said:

If this is something that's super important and you don't mind adding a bit of space to your objects, just add a depth ID. When an object goes into the tree, it gets it's parent's depth + 1. Then then you can simply sort on that.

This is how I've always solved this problem, with a “level” byte that stores the depth of the item in the tree 0=root, 1= first level etc

This gives the added benefit of being able to build the tree view without slow recursion. You can just loop through the levels adding elements and know that their parent ID already exists as they were added in depth order. So a four level tree just needs 4 iterations to build without all that recursive code and stack calls.

Another way to provide a custom sort order (in any way you want) is to just add a long int which stores the order you want to sort them in.

I have used both methods for sorting tree view in MS Access with success.

The problem of finding an order that satisfies certain constraints of the type “A should come before B” is called “topological sorting”. In your case it's particularly trivial because each item has at most one parent. But even the general case is easy to solve, by simply selecting at each step an item that has had all its constraints satisfied already and adding it to the list.

This topic is closed to new replies.

Advertisement