**DATATREE - SORT BRANCH**

I’m still working on handling all “special cases” that show up once I run the algorithms on sharp data.

I encountered a problem with the case below (bundles of open & closed curves in the same plane). Since testing for intersections requires shooting against the right curves (I have zillions of them), I want them bundled together (pictured, a bundle of six curves to the left, and a bundle five curves to the right).

I have these curve-bundles in tree branches, like so (sometimes single curves, sometimes bundles like the curves above):

I would like to pick the “uppermost” of these curves, when there are more than one in the bundle (branch).

So I thought I could sum up all the Z values of each `segment.From.Z` value, then divide the sum by the segment count, and I would have a “height average” value for each curve, by which I could sort each branch and finally pick the one curve with highest such average. That would be the curve to finally probe for a concave minima.

**PROBLEM**

I’ve tried to collect the average values and input them into the Sort component, but it seems I only get arbitrary results. What am I doing wrong? The code I thought would fix the sorting.

```
private void RunScript(DataTree<Polyline> P, ref object A)
{
var tree = P;
var result_tree = new DataTree<double>();
for (var i = 0; i < tree.Branches.Count; i++)
{
var branch = tree.Branches[i];
var path = new GH_Path(i);
for (var j = 0; j < branch.Count; j++)
{
var pline = branch[j];
var n = pline.Count;
// Sum(Z)/Cnt
var z_sum = 0.0;
for (var k = 0; k < n; k++)
{
z_sum += pline.SegmentAt(k).From.Z;
}
double z_avr = z_sum / n;
result_tree.Add(z_avr, path);
}
}
A = result_tree;
}
```

But for some reason this code produces astronomical numbers, why?

And, the sort component doesn’t do anything useful with it either, why? Not my day today.

forum_tree_sort.gh (597.8 KB)

// Rolf