How to sort a woven shuffled stack

Say you have sort of a "woven shuffling situation" going on, sort of like this.

Or that just looks like a regular shuffle for the most part. I'm trying to show the situation where something can be underneath one thing and above another and underneath a few more and above others. Maybe even underneath and above something at the same time. Maybe one this is better:

Take for example this image of the pink line:

The yellow bars show that it only crosses 2 out of the 13 or so lines on the screen. That is, it is always above 10 of the "other things", and it is ~intermingled~ with the top blue and black lines.

That means if this were to be somehow sorted, this would "evaluate" at some point in the first 3 iterations (since there's 3 top lines), and would be guaranteed to evaluate before the other 10 items.

This next image shows an example green line in the middle.

It is intermingled with 3 lines, and above 5, so it's under 4 or so.

Basically, each line can be intermingled with others, going above or going below, or it can be entirely below or entirely above.

The thing I am having difficulty with is figuring this out as a sorting problem. I don't see how to iterate through these items efficiently and how exactly to sort them. Wondering if one might be able to help getting more into the problem and figuring out how to sort these things.

I would like to basically "start from the top of the stack" and perform modifications on all items below the currently selected item, based on some interaction between each item and the currently selected item. This might change the arrangement or layering of the lines, but I guess that can be ignored and it can just be resorted and the process started over or something like that. Yeah I guess that can be ignored, and the main thing is just figuring out a way to (1) sort these items and (2) iterate through them in some sort of order which I don't see yet.

But the reason this gets tricky is because it can be more complicated than that. It can go down into a sort of tree structure like that, which is hard to draw.

Like it can form sort of an octree-like structure, or perhaps even more like a nestled graph.

So the sorting and searching for the order would take into account these paths in the graph somehow. I am having difficulty seeing how it could work. This image just shows like two branches, but there could be dozens, or theoretically lots.