【问题标题】:Sorting an array related to another array对与另一个数组相关的数组进行排序
【发布时间】:2022-01-05 04:34:59
【问题描述】:

我有两个数组,xy,其中 y 是 x 中每个元素的十位的值。现在,我想对y 进行排序。但是,y 的顺序与x 的顺序不同。因此,在对y 中的哪个元素进行排序后,我无法分辨出与x[0] 相关的元素。

也许我想要一个“双重排序”。

【问题讨论】:

  • 我们在说什么语言?是否有任何性能限制?

标签: c# arrays


【解决方案1】:

Array.Sortan overload 接受 两个 数组;一个用于钥匙,一个用于物品。 both的item按照keys数组排序:

int[] keys = { 1, 4, 3, 2, 5 };
string[] items = { "abc", "def", "ghi", "jkl", "mno" };
Array.Sort(keys, items);
foreach (int key in keys) {
    Console.WriteLine(key); // 1, 2, 3, 4, 5
}
foreach (string item in items) {
    Console.WriteLine(item); // abc, jkl, ghi, def, mno
}

所以在你的情况下,这听起来像你想要的:

Array.Sort(y,x); // or Sort(x,y); - it isn't  100% clear

【讨论】:

    【解决方案2】:

    怎么样?

    var selectedArr = new int[] { 1, 3, 5, 7, 9 };
    var unorderArr = new int[] { 9, 7, 5, 3, 1 };
    var orderedArr = unorderArr.OrderBy(o => selectedArr.IndexOf(o));
    

    【讨论】:

    • 这时间复杂度很差,重复时会失败。
    • @user2864740,是的,我同意,但它至少可以工作
    【解决方案3】:

    如果 y 始终是 x 的十位值,则 y 可能不存在 - 您可能应该在需要时直接从 x 计算它的值。

    一般来说,只有当排序算法采用自定义“交换”函数时,才能对并行数组进行排序(无需手动滚动排序算法),您可以通过同时交换两个数组中的元素来实现该函数。 C++ 中的 std::sort 和 C 中的 qsort 不允许这样做。

    同样在一般情况下,考虑元素是一对项目的单个数组,而不是每个项目的并行数组。这使得使用“标准”算法更容易。

    【讨论】:

      【解决方案4】:

      如果我们有两个复杂对象数组,并且想根据两个数组之一对它们进行排序,那么我们可以使用下一种方法:

      // We want to sort "people" array by "Name" and
      // accordingly to it reorder "countries" array.
      Person[] people = new Person[]
      {
          new Person {Name = "Fill"},
          new Person {Name = "Will"},
          new Person {Name = "Bill"},
      };
      
      Country[] countries = new Country[]
      {
          new Country {Name = "Canada"},
          new Country {Name = "UK"},
          new Country {Name = "USA"}
      };
      
      // Here we sort "people" array, but together with each "Person"
      // in sorted array we store its "index" in unsorted array. Then we
      // will use this "index" to reorder items in "countries" array.
      var sorted = people
          .Select((person, index) => new {person, index})
          .OrderBy(x => x.person.Name)
          .ToArray();
      
      // Here "people" array is sorted by "Name", and
      // "contries" array is reordered accordingly to it.
      people = sorted.Select(x => x.person).ToArray();
      countries = sorted.Select(x => countries[x.index]).ToArray();
      

      另一种方法是使用方法Array.Sort with IComparer 的重载。首先我们应该实现IComparer

      private class PeopleComparer : IComparer<Person>
      {
          public int Compare(Person x, Person y)
          {
              return x.Name.CompareTo(y.Name);
          }
      }
      

      然后我们可以对我们的两个数组进行排序:

      Array.Sort(people, countries, new PeopleComparer());
      

      complete sample 演示了这两种方法。

      【讨论】:

        猜你喜欢
        • 2020-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多