2

I am trying to write a sorting algorithm visualizer and am trying to return an array of all the different iterations/forms of the array being sorted. Here is my code:

const bubbleSort = (arrToBeSorted) => {
  isSorted = false;
  finalRes = [arrToBeSorted]   // Include original array that needs to be sorted;
  while (!isSorted) {
    isSorted = true;
    for (let i = 0; i < arrToBeSorted.length - 1; i++) {
      if (arrToBeSorted[i] > arrToBeSorted[i + 1]) {
        toBeSwapped = arrToBeSorted[i];
        arrToBeSorted[i] = arrToBeSorted[i + 1];
        arrToBeSorted[i + 1] = toBeSwapped;
        isSorted = false; 
        finalRes.push(arrToBeSorted); // Append to finalRes array the array that has been modified this iteration
        
      }
    }
  }
  return finalRes;
};

Bubble Sort itself works fine, but my issue is that when I return finalRes, I just get the sorted array multiple times (the number of iterations the sorting algorithm has conducted)

E.G. if I pass [5, 21, 11, 17] as the arrToBeSorted I get [[5, 11, 17, 21], [5, 11, 17, 21], [5, 11, 17, 21]] as the return of the finalRes

Why is this happening? Shouldn't it be appending each iteration of the modified array to the finalRes array?

I tried looking at this answer but it doesn't help me.

Thanks in advance!

Tejas_hooray
  • 606
  • 1
  • 6
  • 16
  • 1
    The solution is that I had to use "finalRes.push(arrToBeSorted.slice())" to push a shallow copy to the finalRes array. – Tejas_hooray Feb 12 '21 at 02:18

0 Answers0