2

I'm using Array.Sort() to sort an array of doubles into ascending order. And then in some cases I do a Reverse() to change the order. But ideally I'd like to preserve my original array. Does C# have a simple, native sort for arrays that outputs to a new array rather than sorting the existing array in-place?

1
  • Use the OrderBy Linq Method Commented May 22, 2015 at 19:07

1 Answer 1

10

You can use LINQ to do that:

var result = source.OrderBy(x => x).ToArray();

or for descending order:

var result = source.OrderByDescending(x => x).ToArray();

or you can create new array first and than sort it:

var newArray = (double[])source.Clone();
newArray.Sort();

I would expect the latter to be faster, but you should probably measure it to be sure.

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

1 Comment

It is faster especially with big arrays to use Array.Sort(). Two reasons: OrderBy() first need to extract all keys (do the projection by executing the lamba on all values) so it iterates once over the whole array before doing the sorting. Then it uses quicksort internally whereas Array.Sort() use introsort (a mix between quicksort and heapsort) which gives better average performance. By the way it is faster to copy the array using Array.Copy instead of creating a clone.

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.