2016-03-04 122 views
1

我正在構建一個排序算法(選擇排序),並且已經能夠完成它。但是,如果我想添加一個臨時變量,它存儲了排序的數組,它似乎是馬上改口數組排序:臨時變量不存儲在Javascript中

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

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

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].

請INF orm我的錯誤。 `

+0

http://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript –

回答