I’m have a class with two methods, A QuickSort() and a ReverseArray(). When I pass in the array, it’ll first call QuickSort(), and then ReverseArray(), however when it gets to ReverseArray(), it reverses the sorted array from QuickSort() instead of reversing the original Array that is made. What am I doing wrong? Any advice would be much appreciated.
public class Program
{
private readonly int[] ProgramArray = new int[10] ;
public Program(int[] array)
{
ProgramArray = array;
QuickSort();
ReverseArray();
}
public void QuickSort()
{
var newarray = new int[10];
newarray = ProgramArray;
Array.Sort(newarray);
Print(newarray, "QuickSort");
}
public void ReverseArray()
{
var newarray = new int[10];
newarray = ProgramArray;
Array.Reverse(newarray);
Print(newarray, "Reversed");
}
public static void Print(int[] array, string methodname)
{
int[] newarray = array;
Console.Write(string.Format("{0}: ", methodname));
for (int i = 0; i < newarray.Length; i++)
{
Console.Write(newarray[i] + " ");
}
Console.Write("\n");
}
static void Main(string[] args)
{
var array = new int[10] { 12, 24, 3, 44, 5, 16, 7, 34, 23, 34 };
var program = new Program(array);
}
An array is a reference type. You are working on the same reference throughout your code base.
If you want a copy of the array, you need to copy it.
Here,
newarrayis not a copy of the array, but a copy of the reference toProgramArray:Use the
Copymethod defined onArrayin order to create copies:Also, I suggest reading about the differences between value types and reference types.