【问题标题】:Two variable sorting algorithm二变量排序算法
【发布时间】:2011-04-25 17:32:15
【问题描述】:

我正在寻找一种从西到东和从南到北对位置点(纬度和经度)进行排序的算法。

排序时,点应从西、南开始排序。比较两点时,先比较经度。值越大(越西)点在列表中越高。如果两个点具有相同的经度,不太可能但可能,则比较两个点的纬度。最低值(越靠南)在列表中的位置越高。

这个算法是否存在于某个地方?也许在 C# 中?

ps- 这些计算将仅限于美国大陆内的点。不会有负纬度/经度值。

【问题讨论】:

  • 我不清楚为什么这需要比 .NET Framework 中的普通内置排序函数更复杂的东西(例如List.SortEnumerable.OrderBy。)排序的比较函数正如您所描述的那样,大概会先比较经度,然后再比较纬度。
  • 在此处查看第二个答案:stackoverflow.com/questions/289010/c-list-sort-by-x-then-y。或者,定义您自己的比较函数并将其传递给任何标准排序算法。
  • 我会知道如何在 php 中做到这一点,或者尝试查看 LINQ

标签: c# sorting


【解决方案1】:
using System.Linq;

var sortedPoints = points.OrderByDescending(p => p.Longitude).ThenBy(p => p.Latitude);

【讨论】:

  • 我想他先说的是经度。
【解决方案2】:

.NET 中没有开箱即用的算法(C# 是一种语言,通常不实现算法,您通常会在 .NET 基类库中找到它)。

但是,您可以轻松地创建一个带有Latitude/Longitude 属性的Coordinates 结构/类(我认为每个都是double),然后实现IComparable<T>

然后实现看起来像这样:

public class Coordinates : IComparable<Coordinates>
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }

    public int CompareTo(Coordinates other)
    {
        // If the other instance is null, assume that
        // it is at 0,0?  You need to make that determination.
        if (other == null) return 1;

        // Compare longitude (double implements
        // IComparable<double>.
        int comparison = Longitude.CompareTo(other.Longitude);

        // If not 0, return the value.
        if (comparison <> 0) return comparison;

        // Compare latitude.  Inverse the result, as the more
        // south point (closer to 0) is greater.
        // Just return the value, if they are different, the
        // comparison value will be correct, if they are the
        // same, then comparison will be 0.
        return -Latitude.CompareTo(other.Latitude);
    }
}

现在,您可以填充这些实例,将它们放在一个数组中并将其传递给static Sort method on the Array classSort 方法将使用 IComparable&lt;T&gt; 实现对数组进行排序。

或者您可以将它们放在List&lt;T&gt; 中(可能更容易,因为您可能事先不知道元素的数量),然后在实例上调用Sort method;它也将使用IComparable&lt;T&gt; 实现对自身进行排序。

您还提到了两点相同。由于LatitudeLongitude 表示为double,因此您将面临浮点错误的风险。如果您想减轻这些错误,您可以轻松地将属性更改为decimal(这可以保证精度,直到某个点);这样,您将保证精度,并且它实现了IComparable&lt;decimal&gt;,这意味着IComparable&lt;Coordinates&gt; 的实现将只适用于开关。

【讨论】:

  • 经常将 Lat 和 lon 缩放为足够大的整数以达到所需的精度。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-05
  • 2012-03-05
  • 1970-01-01
  • 2019-05-21
  • 2020-11-12
  • 1970-01-01
  • 2018-07-05
相关资源
最近更新 更多