3

I Have two arrays named weights and values. I wanted to sort Values based on the sorting of Weights. That works perfectly fine by doing

Array.Sort(Weights,Values);

This gives me arrays sorted in ascending order. I wanted to do the same sorting in Descending order. Is there a better way to do without using Array.Reverse(Weights) and Array.Reverse(Values)

2
  • How long are Weights and Values? Commented May 8, 2016 at 1:00
  • Write a custom comparator. Commented May 8, 2016 at 1:01

2 Answers 2

5

You'll have to use this overload and provide a custom IComparer<T>. The relatively new Comparer<T>.Create method makes this a lot easier because you can simply turn a delegate or lambda expression into an IComparer<T> without having to code a full implementation yourself. It's not clear from the question what the datatype of Weights and Values are, but here's an example using double[] and int[] respectively:

var Weights = new [] { 1.7, 2.4, 9.1, 2.1, };
var Values = new [] { 7, 9, 5, 3, };

Array.Sort(Weights, Values, Comparer<double>.Create((x, y) => y.CompareTo(x)));

And just for fun, here's a solution using LINQ:

var pairs = Weights.Zip(Values, Tuple.Create);
var orderedPairs = pairs.OrderByDescending(x => x.Item1);

I'd also recommend that you consider using a class to store weights and values together rather than as two separate arrays.

Sign up to request clarification or add additional context in comments.

2 Comments

Than you for the answer. Weights is a int array and values is double array. How can i handle that scenario using the code above ? Can you provide an example ?
@Srini All you'd have to do is change Comparer<double> to Comparer<int>.
2

First, create a structure that holds the corresponding items.

var items =
    Weights
        .Select((weight, index) =>
            new
            {
                Weight = weight,
                Value = Values[index]
            }
        )
        .OrderByDescending(item => item.Weight)
        .ToArray();

Then you can get the sorted array back:

Weights = items.Select(item => item.Weight).ToArray();
Values = items.Select(item => item.Value).ToArray();

But you may also try one of the answers here:
Better way to sort array in descending order

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.