I'm trying to write a bubble sort animation - for that I want to put all the iteration in the separate array and then reproduce them. But the array
variable acts weird - all the console.dir(array)
outputs are sorted arrays, so in the pool
appears to be 9 identical arrays [[1 ,2 ,3], [1, 2, 3] ... ]
I expect to see all the iteration of the sorting algorithm: [[2, 3, 1], [2, 1, 3] ... ]]
Can anyone tell me what am I doing wrong, and the most important, why array
array is always sorted?
Note: Snippet works here, but doesn't work correctly in browser, or jsfiddle
Code snippet:
const pool = [];
const bubbleSort = (array) => {
const len = array.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
if (array[j] > array[j + 1]) {
const tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
}
pool.push(array);
console.dir(array);
}
}
}
bubbleSort([3, 2, 1]);
console.log(pool);