Search code examples
javascriptarraysalgorithmsortingbubble-sort

How to insert an array to another array at each iteration of a for loop in javascript


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?


Solution

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