0

I'm trying to sort an array to find the mean of it. After finding the median I'm looking to continue using the array. When using the code,

            double[] views, viewssorted;
            views = new double[] {9.0, 1111.0,  2.0 };
            viewssorted = views;
            Array.Sort(viewssorted);

both my viewssorted and views arrays get sorted. How do I make it so that only viewssorted gets sorted?

4
  • By creating a copy of the array. Commented Jul 11, 2017 at 19:34
  • You don't have two arrays; you have two variables that point to the same array. Commented Jul 11, 2017 at 19:36
  • 1
    How does sorting an array help you in finding the mean? Commented Jul 11, 2017 at 19:37
  • it was meant to be median Commented Jul 11, 2017 at 19:43

3 Answers 3

1

Your problem is that arrays are essentially classes and as such reference types. A reference type does not hold a value but rather points to an area in your memory.

When you write viewssorted = views; you are assigning the same reference you have in views to viewssorted. They are essentially the same object referenced by two variables.

To create a copy of the array, but with the same internal references (in your case the same double values), use Array.Clone().

This would be

viewssorted = (double[])Array.Clone(views);
Sign up to request clarification or add additional context in comments.

Comments

0

When using

viewssorted = views;

viewssorted and views are references to the same array. Thus, any change in the first will be reflected in the second.

You should use Array.Clone to make a copy of the array.

viewssorted = (double[]) views.Clone();;

Comments

0

Arrays are reference types in C#, that's why they both sort.

You can do

views.CopyTo(viewssorted)

Or

viewssorted = views.Clone()

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.