【问题标题】:Sorting pair of integers排序整数对
【发布时间】:2017-12-14 07:19:57
【问题描述】:

我有一个包含大约 100k 个整数对的列表,比如这些:

0, 12
0, 14
0, 1
0, 8
0, 2
0, 4
0, 3
1, 5
1, 11
1, 8
1, 2
2, 7
2, 9
2, 4
2, 5
2, 13
3, 12
3, 10
3, 4
3, 6
...

我需要对它们进行排序

0, 1
0, 2
0, 3
0, 4
0, 8
0, 12
0, 14
1, 2
1, 5
1, 8
1, 11
2, 4
2, 5
2, 7
2, 9
2, 13
3, 4
3, 6
...

目前我在做:

myList.Sort(comparer);

当比较器定义为:

class EdgeIntersectComparer : IComparer<EdgeIntersect>
{
   public int Compare(EdgeIntersect l1, EdgeIntersect l2)
   {
       if (l1.V1 < l2.V1)
          return -1;
       if (l1.V1 > l2.V1)
          return 1;

       if (l1.V2 < l2.V2)
          return -1;
       if (l1.V2 > l2.V2)
          return 1;

       return 0;
   }
}

我可以做些什么来提高执行速度?有没有更聪明的方法来解决这个问题?

谢谢。

编辑:

经过myList.OrderBy(e =&gt; e.V1).ThenBy(e =&gt; e.V2)测试,速度较慢。

【问题讨论】:

  • 目前列表按对的第一个整数排序...
  • @Chris:边被定义为一对整数...
  • 我不知道它是否会更快(可能不会)但您可以尝试使用 Linq:var sorted = myList.OrderBy(e =&gt; e.V1).ThenBy(e =&gt; e.V2);
  • “我能做些什么来提高执行速度?有没有更聪明的方法来解决这个问题?”...不确定是否有人正在阅读该部分。

标签: c# .net sorting graphics quicksort


【解决方案1】:

您在已删除的帖子中评论 V1 已排序。

除 V1 之外,列表已经排序。

我使用 V1 已经排序的数据进行了测试,但 V2 使用随机数初始化。我发现这比你的方法更快:

myList = myList.GroupBy(x => x.V1).SelectMany(x => x.OrderBy(y => y.V2)).ToList();

V1 已排序时有效。

【讨论】:

    【解决方案2】:

    作为一种可能的选择,您可以尝试使用数组而不是列表。 (这取决于您的上下文)。如果你不能:

    假设:

     public class Pair
    {
        public int First { get; private set; }
        public int Second { get; private set; }
        public Pair(int first, int second)
        {
            this.First = first;
            this.Second = second;
        }
    }
    

    List 是如何按第一项排序的,也许是这样的?不确定这是否会更快:

        public static List<Pair> FullOrderedList(List<Pair> SemiOrderedList)
        {
            List<Pair> FList = new List<Pair>();
            List<Pair> demi = new List<Pair>();
            int MaxNumber = SemiOrderedList.Count;
            int compared = 0;
            for (int i = 0; i < MaxNumber; i++)
            {
                int first = SemiOrderedList[i].First;
                if (compared == first)
                {
                    demi.Add(SemiOrderedList[i]);
                }
                else
                {
                    compared++;
                    FList.AddRange(demi.OrderBy(x => x.Second));
                    demi.Clear();
                }
            }
            return FList;
        }
    

    【讨论】:

      【解决方案3】:

      通过优化比较器可以小幅提高速度:

      if (l1.V1 == l2.V1)
      {
         if (l1.V2 > l2.V2) return 1;
         else return -1;
      }
      else if (l1.V1 < l2.V1)
                return -1;
      else return 1;
      

      最多检查 2 个语句,而不是 4 个。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-29
        • 1970-01-01
        • 1970-01-01
        • 2012-12-25
        • 1970-01-01
        • 2012-04-09
        相关资源
        最近更新 更多