The following code changes the elements in the array
variable. I would expect changes in sortedArray
but it make changes in both. I never have array
on the left hand side of any equals sign. I'm never setting array
to any value, yet I see changes in it in the debugger when I watch.
static int[] SortArray(int[] array)
{
int[] sortedArray = array;
while (!IsSorted(sortedArray))
{
for (int i = 0; i < array.Length-1; i )
{
if( sortedArray[i] > sortedArray[i 1])
{
sortedArray[i] = array[i 1];
sortedArray[i 1] = array[i];
}
}
}
return sortedArray;
}
Before the SortArray
method is called, array
is (8, 3, 1, 6, 4), and when the method is done, array
is (1, 1, 1, 4, 4).
CodePudding user response:
Take a look at the statement int[] sortedArray = array;
. With this statement, you're assigning array
to sortedArray
. Both variables now point to the same array in memory so any change made to it via one of them will also be visible via the other one (since they both point to the same array!).
It seems you meant to copy the array. You could do this by using Array.Copy
, or even manually:
int[] sortedArray = new int[array.Length];
for (int i = 0; i < array.Length; i)
{
sortedArray[i] = array[i];
}