简体   繁体   中英

How do I assign the new arrangement of an array to another array in C#?

Lets say I get the following input:

12 15
13 19
9 20
5 40
20 10

I want to sort this list using quicksort based on the first values of the tuples (12, 13, 9, 5, 20). So I'd create two arrays, A and B, A for 12, 13, 9, 5, 20 and B for 15, 19, 20, 40, 10.

I'll sort A using quicksort and get 5, 9, 12, 13 and 20. How do I get the other half of the values to change its positions so that it matches the initial tuples? So if I have 5, 9, 12, 13 and 20 I also want to get 40, 20, 15, 19 and 10 in this order.

The question here is: Why are you creating two arrays in the first place?

How about you create a small structure that stores the two components (or just use the tuple type C# provides since C#7), put that in an array and sort by one of the members.

An example would be to use something like this:

struct Element
{
    public int A;
    public int B;
}

And then in your code, you just sort by A. When you then read from the array, you get both in the desired order. If you need them in two separate arrays later, you can simply extract the values again.

You can sort them as tuples and then create a and b using Select :

var data = new (int, int)[]
{
    (12, 15),
    (13, 19),
    (9, 20),
    (5, 40),
    (20, 10)
};

Array.Sort(data, (left, right) => left.Item1.CompareTo(right.Item1));

var a = data.Select(item => item.Item1).ToArray();
var b = data.Select(item => item.Item2).ToArray();

You might want to ask yourself if you really need the two arrays in the first place. The single array ( data ) holds everything you need and allows you to easily get the corresponding value.

If you have two arrays a and b then you can sort them using method Array.Sort(keys, values) . The items of both arrays are sorted according to the values of the keys array:

int[] a = {12, 13, 9, 5, 20};
int[] b = {15, 19, 20, 40, 10};
Array.Sort(a, b);

This will produce the next result:

5,   9, 12, 13, 20
40, 20, 15, 19, 10

Here is complete sample .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM