Build a Sorting Visualizer - Build a Sorting Visualizer

Tell us what’s happening:

I’m consistently failing Test 19.

Your code so far

const genBtn = document.getElementById("generate-btn");
const startingArray = document.getElementById("starting-array");
const arrayContainer = document.getElementById("array-container");
const sortBtn = document.getElementById("sort-btn");

function generateElement() {
  return Math.ceil(100 * Math.random());
}

function generateArray() {
  return Array.from({length: 5}, ()=>generateElement());
}

function generateContainer() {
  return document.createElement("div");
}

function fillArrContainer(htmlEl, arr) {
   htmlEl.innerHTML = arr.map(num => {
    return `<span>${num}</span>`;
  }).join("");
}

function isOrdered(int1, int2) {
  return (int1 <= int2);
}

function swapElements(intArr, index) {
  if (!isOrdered(intArr[index], intArr[index + 1])) {
    [intArr[index], intArr[index + 1]] = [intArr[index + 1], intArr[index]];
  }
}

function highlightCurrentEls(htmlEl, index) {
  htmlEl.children[index].style.border = "1px dashed red";
  htmlEl.children[index + 1].style.border = "1px dashed red";
}

let arrayToUse = []

genBtn.addEventListener("click", () => {
  arrayContainer.innerHTML = "";
  arrayContainer.appendChild(startingArray);
  startingArray.innerHTML = "";
  arrayToUse = generateArray();
  fillArrContainer(startingArray, arrayToUse);
})



sortBtn.addEventListener("click", () => {

  if (!arrayToUse || arrayToUse.length === 0) return;

  Array.from(arrayContainer.children).forEach(child => {
    if (child !== startingArray) child.remove();
  });

  const arr = [...arrayToUse];
  const n = arr.length;

  for (let i = 0; i < n - 1; i++) {
    let swapped = false;

    for (let j = 0; j < n - 1; j++) {
      if (i === 0 && j === 0){
        highlightCurrentEls(startingArray, j);
        continue;
      } 

      const div = generateContainer();
      fillArrContainer(div, arr);
      highlightCurrentEls(div, j);
      arrayContainer.appendChild(div);

      if (!isOrdered(arr[j], arr[j + 1])) {
        swapElements(arr, j);
        swapped = true;
      }
    }

    if (!swapped) break;
  }

  const finalDiv = generateContainer();
  finalDiv.style.border = `4px solid green`
  fillArrContainer(finalDiv, arr);
  arrayContainer.append(finalDiv);
});


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36

Challenge Information:

Build a Sorting Visualizer - Build a Sorting Visualizer

When I run your code, I see that the first two array elements in the first iteration of the loop are not swapped, as below:

The second div should be 7, 84, 46, 16, 11.

So work on that.

With the help, I passed the test. THANKS…