public void BuildTree(KDNode currentNode, List <Feature> features, bool useXAxis) { if (useXAxis) { features = features.OrderBy(i => i.X).ToList(); } else { features = features.OrderBy(i => i.Y).ToList(); } Feature med = FeatureHelper.GetMedianFeatureFromList(features); var node = InsertNode(currentNode, med, true); var splitFeatures = FeatureHelper.SplitFeatures(features, features.IndexOf(med)); List <Feature> leftSplit = splitFeatures[0].ToList(); List <Feature> rightSplit = splitFeatures[1].ToList(); if (leftSplit.Count <= 1) { if (leftSplit.Count == 1) { InsertNode(node, leftSplit[0], useXAxis); } } else { this.BuildTree(node, leftSplit, !useXAxis); //alternate dimension each level we build } // Do the same for the right points if (rightSplit.Count <= 1) { if (rightSplit.Count == 1) { InsertNode(node, rightSplit[0], useXAxis); } } else { BuildTree(node, rightSplit, !useXAxis); } }
public void SplitFeatureList_Works_As_Expected() { var features = new List <Feature>(); features.Add(new Feature("place1", 1, 2)); features.Add(new Feature("place2", 2, 2)); features.Add(new Feature("place3", 3, 2)); features.Add(new Feature("place4", 4, 2)); features.Add(new Feature("place5", 5, 2)); features.Add(new Feature("place6", 6, 2)); features.Add(new Feature("place7", 7, 2)); var expectedList1 = new List <Feature>(); expectedList1.Add(new Feature("place1", 1, 2)); expectedList1.Add(new Feature("place2", 2, 2)); expectedList1.Add(new Feature("place3", 3, 2)); var expectedList2 = new List <Feature>(); expectedList2.Add(new Feature("place5", 5, 2)); expectedList2.Add(new Feature("place6", 6, 2)); expectedList2.Add(new Feature("place7", 7, 2)); var outcomeLists = FeatureHelper.SplitFeatures(features, 3); for (int i = 0; i < outcomeLists[0].Count; i++) { Assert.Equal(outcomeLists[0][i].Name, expectedList1[i].Name); } for (int i = 0; i < outcomeLists[1].Count; i++) { Assert.Equal(outcomeLists[1][i].Name, expectedList2[i].Name); } }