我一直在尝试实现 QuickSort 算法以非常具体的方式对坐标列表进行排序。等等,让我告诉你我的意思。下图是我坐标的当前顺序。它们的顺序是从左到右,然后是从上到下。我们唯一可以访问的是它们的坐标(即顶部、左侧坐标,表示为它们与框架顶部和左侧的距离)
我以为我可以使用 QuickSort 算法来执行该任务,但直到现在它还没有按预期工作。我没有得到我想要的顺序,而是得到了从上到下的顺序。
所以我的代码看起来像这样:
public class Point{
string name;
float Top;
float Left;
//Constructor and so on
}
public class QuickSortMethods{
public List<Point> QuickSortPoints(List<Point> list) {
if (list.Count <= 1) return list;
int pivotIndex = list.Count / 2;
Point pivot = list[pivotIndex];
List<Point> left = new List<Point>();
List<Point> right = new List<Point>();
for (int i = 0; i < list.Count; i++) {
if (i == pivotIndex) continue;
if (Round(list[i].Top) < Round(pivot.Top)) {
left.Add(list[i]);
}
else {
right.Add(list[i]);
}
}
List<Point> sorted = QuickSortPoints(left);
sorted.Add(pivot);
sorted.AddRange(QuickSortPoints(right));
return sorted;
}
private double Round(float f){
// This is because we don't want slight fluctuations in Left variable to change the result
// This is, for instance, for our I point in the image above.
return Math.Round(f,1);
}
}
现在我从另一个脚本中这样调用它:
public static void Main(string[] args)
{
//The Point list is made before, we actually get it from elsewhere, but for the sake of this example, i'll do it above
//but keep in mind that my problem is not when creating the list.
List<Point> pointList= new List<Point>();
pointList.Add(new Point(A,0.1,0.4));
.
.
pointList.Add(new Point(T, 0.2,0.6));
//You get the idea.
//Now i do the quicksort
var quickSort= new QuickSortMethods();
var quickSortedResult = quickSort.QuickSortPoints(pointList);
}
因此在示例中,它返回 E、I、Q、F、J、K、L 而不是 E、F、G、H、I、J、K、L。 现在我知道这来自我只是检查每个点是否有一个比我的枢轴更大的顶部,但我已经尝试了许多其他条件,这些条件给出了很多不同的结果,但从来没有我第一个想要的。所以这是我的问题:我尝试使用 QuickSort 是不是错了?如果是这样,您对如何执行此操作有什么建议吗?或者你知道我应该使用哪种条件而不是
if (Round(list[i].Top) < Round(pivot.Top))
?
我不太确定我是否已经足够清楚,所以如果您有任何问题可以帮助您了解我的情况,请不要犹豫!