Home > Software engineering >  How to insert an array to another array at each iteration of a for loop in javascript
How to insert an array to another array at each iteration of a for loop in javascript

Time:08-01

I have a function to bubble sort and I want to save the array after each swap into another array. The bubble sort is working properly and I can log the array after each swap to the console. But I cant seem to push to the other array properly.

Here's my code :

var arr = [5, 4, 3, 2, 1];
var steps = [];

function bubbleSort() {
  for (let i = 0; i < arr.length - 1; i  ) {
    for (let j = 0; j < arr.length - i - 1; j  ) {
      if (arr[j] > arr[j   1]) {
        swap(arr, j, j   1);
      }
      var temp = arr;
      console.log(temp);
      steps.push(temp);
    }
  }
  console.log(steps);
}

const swap = (a, x, y) => {
  var temp = a[x];
  a[x] = a[y];
  a[y] = temp;
};

bubbleSort();

Here's a screenshot of the console :

screenshot of console

It's only when I try to use get a hold of the array at each step that it isn't showing properly? what do I do?

CodePudding user response:

I think clonning the array could work ? var temp = [...arr];

var arr = [5, 4, 3, 2, 1];
var steps = [];

function bubbleSort() {
  for (let i = 0; i < arr.length - 1; i  ) {
    for (let j = 0; j < arr.length - i - 1; j  ) {
      if (arr[j] > arr[j   1]) {
        swap(arr, j, j   1);
      }
      var temp = [...arr];
      console.log(temp);
      steps.push(temp);
    }
  }
  console.log(steps);
}

const swap = (a, x, y) => {
  var temp = a[x];
  a[x] = a[y];
  a[y] = temp;
};

bubbleSort();

CodePudding user response:

You are inserting the Reference of the Temp-Array and not the actual content. This way, you store multiple times the reference and at the End you are presented with all those reference pointing to the last version of your temp Array.

You can use the destructuring assignment of an array, to create an easy shallow copy to be stored.

var arr = [5, 4, 3, 2, 1];
var steps = [];

function bubbleSort() {
  for (let i = 0; i < arr.length - 1; i  ) {
    for (let j = 0; j < arr.length - i - 1; j  ) {
      if (arr[j] > arr[j   1]) {
        swap(arr, j, j   1);
      }
      var temp = arr;
      console.log(temp);
      // Changed to destructuring assignment
      steps.push([...temp])
    }
  }
  console.log(steps);
}

const swap = (a, x, y) => {
  var temp = a[x];
  a[x] = a[y];
  a[y] = temp;
};

bubbleSort();

  • Related