1

I am building a sorting algorithm (Selection Sort) and have been able to complete it. However, if I want to add a temporary variable, which stores the unsorted array, it seems to be immediately changed to the sorted array:

 var A = [-8, 1, 77, -99, 3, 5];
 function findMin(A,startIndex,endIndex) {
 var temp = startIndex;
 for(var x = startIndex; x <= endIndex; x++){


 if(A[temp] > A[x]) {

   temp = x;

}

}
return temp;
}
function swapNumbers(A, index1, index2) {
var temp_2 = A[index1];
A[index1] = A[index2];
A[index2] = temp_2;

return A;
}

function sort(A) {
var endofArray = A.length - 1;
var temp3 = A;
var Asorted = [];
for(var i = 0; i < A.length; i++) {
    swapNumbers(A, i, findMin(A, i, endofArray));

}
Asorted = A;
console.log("The unsorted array was " + "[" + temp3 + "]" 
+ "." + " The sorted array is " + "[" + Asorted + "]" + "."); 
return Asorted; /*subsitute return for 
console.log() to display results*/
}
sort(A);

The temp3 in console.log("The unsorted array was " + "[" + temp3 + "]" + "." + " The sorted array is " + "[" + Asorted + "]" + "."); seems to output:

The unsorted array was [-99,-8,1,3,5,77]. The sorted array is [-99,-8,1,3,5,77].

instead of:

The unsorted array was [-8, 1, 77, -99, 3, 5]. The sorted array is [-99,-8,1,3,5,77].

Please inform me of my mistake. `

1 Answers1

2

When you assign temp3 to A, you're basically just pointing to the A array in memory, not actually copying the array. Try:

var temp3 = A.slice();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

tutley
  • 446
  • 3
  • 9