[英]How to sort two arrays by same index?
我有 2 個數組。 我想按相同的索引號對它們進行排序。 例如我有這些:
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}
我想按 b 的索引對 a 進行排序 -> 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"}
不太清楚你的意思。 在使用b
對a
進行排序a
? 如果是這樣,這很容易,因為我們仍然可以使用上述內容。 將a
和c
壓縮到一個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];
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.