MurDaD
MurDaD

Reputation: 362

JavaScript array sorts itself

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

Upvotes: 1

Views: 560

Answers (2)

user1859318
user1859318

Reputation: 1

you have to understand two things:

  • the variable array refers to a mutable array. This means that each time you swap two elements, the array is modified
  • when you do pool.push(array), you push a reference into pool.

In your code, you push n times the same reference in pool. So, you have only 2 arrays in memory: pool and array (i.e. [3,2,1] in your example)

Each time you modify array (by swapping elements), you modify all the arrays (in fact the unique array) stored in pool.

So, if you want to take a snapshot you have to store a copy of your array in pool: pool.push(array.slice())

Concerning the "weird" behaviour of console.dir, this comes from the asynchronous nature of this function. See console.log() async or sync?

Upvotes: 0

cross19xx
cross19xx

Reputation: 3487

The solution I think has to do with the fact that JavaScript arrays sort of maintain something of a "pass by reference" kind of situation when you push to the pool stack. You can try

pool.push(array.slice()); // This creates a new instance of the array

You can also read this documentation for clarification on mutability of arrays

Upvotes: 3

Related Questions