1

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

3
  • I've tried multiple times in jsfiddle and in angular application - same result. BTW, jsfiddle link: jsfiddle.net/asqdg79b/2 Commented Feb 28, 2020 at 8:11
  • ha, interesting - it works only in REPL :) Commented Feb 28, 2020 at 8:12
  • If you insert code correctly - you can run it directly on SO! Fixed that for you Commented Feb 28, 2020 at 8:12

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.