如何按相同的索引对两个数组排序

本文关键字:两个 数组排序 何按相 索引 | 更新日期: 2023-09-27 18:18:26

我有两个数组。我想按照相同的索引号对它们排序。例如:

int[] a = {120, 60, 50, 40, 30, 20};
int[] b = {12, 29, 37, 85, 63, 11};
Array.Sort(b); // Now, b is -> b = {11, 12, 29, 37, 63, 85}

我想对a按b的索引排序-> a = {20, 120, 60, 50, 30, 40}

如果我也有字符串数组c -> c = {"b", "u", "r", "s", "a", "1"}

我想按b的索引对c排序-> c = {"1", "b", "u", "r", "a", "s"}

我该怎么做?提前感谢,问候。

如何按相同的索引对两个数组排序

使用接受两个输入数组的Array.Sort<TKey, TValue>(TKey[] keys, TValue[] items),一个是键数组,另一个是要使用这些键进行排序的项数组。这里,对你来说,b是你的钥匙,a是你的物品。

:

Array.Sort(b, a);

将使用b的键对a的项进行排序。

我想按b的索引对c排序-> c = {"1", "b", "u", "r", "a", "s"}

我不太清楚你的意思。在同一时间,你排序a使用b ?如果是这样,这很简单,因为我们仍然可以使用上面的方法。将ac压缩为Tuple<int, string>数组。
var d = a.Zip(c, (x, y) => Tuple.Create(x, y)).ToArray();

:

Array.Sort(b, d);

。然后提取片段:

a = d.Select(z => z.Item1).ToArray();
c = d.Select(z => z.Item2).ToArray();

或者,如果您需要使用相同的键集对许多数组进行排序:

int[] indexes = Enumerable.Range(0, b.Length).ToArray();
Array.Sort(b, indexes);

现在您可以使用indexes对所需的所有数组进行排序。例如:

a = indexes.Select(index => a[index]).ToArray();
c = indexes.Select(index => c[index]).ToArray();

等。。

这里可能有一些小的编码错误。

// a dirty and inefficient way of doing it, 
// but should give you a heads up to get started
    // you obviously dont want to modify array b, so making a copy
    int[] c = Arrays.copyOf(b, b.length);
    // now apply a sort on 'c' and apply the same operation on 'a' when modifying 'c'
    // -> applying a bubble sort - > inefficient
    for( int i = 0; i < c.length ; i ++) {
        for( int j = 0 ; j < c.length - 1; j ++) {
            if(c[j] > c [j+1]) {
                c[j] = c[j] + c[j+1];
                c[j+1] = c[j] - c[j+1];
                c[j] = c[j] - c[j+1];
                // apply the same to a
                a[j] = a[j] + a[j+1];
                a[j+1] = a[j] - a[j+1];
                a[j] = a[j] - a[j+1];
            }
        }
    }