Javascript

时间:2016-03-04 16:20:26

标签: javascript arrays sorting selection-sort

我正在构建排序算法(选择排序)并且已经能够完成它。但是,如果我想添加一个存储未排序数组的临时变量,它似乎会立即更改为已排序的数组:

 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);

temp3中的console.log("The unsorted array was " + "[" + temp3 + "]" + "." + " The sorted array is " + "[" + Asorted + "]" + ".");似乎输出:

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

而不是:

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

请告诉我我的错误。    `

1 个答案:

答案 0 :(得分:2)

当你将temp3分配给A时,你基本上只是指向内存中的A数组,而不是实际复制数组。尝试:

var temp3 = A.slice();

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