Build a Sorting Visualizer - Build a Sorting Visualizer

Tell us what’s happening:

I’m unable to pass the test no 18, 19, and 20. please someone explain what i am doing wrong, I’ve also tried writing the code with the help of AI but keep failing the tests mentioned above

Your code so far

<!-- file: index.html -->

/* file: styles.css */

/* file: script.js */

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:156.0) Gecko/20100101 Firefox/156.0

Challenge Information:

Build a Sorting Visualizer - Build a Sorting Visualizer

GitHub Link: freeCodeCamp/curriculum/challenges/english/blocks/lab-sorting-visualizer/6716249b5405164036fd0b0d.md at main · freeCodeCamp/freeCodeCamp · GitHub

Hi

Can you please post your code.

Welcome back @moizsydiki,

There are two ways you can format your code to make it easier to read and test:

  1. After you copy/paste your code into the editor, select it by dragging your cursor over it then click the (</>) button in the toolbar to automatically wrap your code in backticks. (You can click on the animated demo image below to enlarge it.)

  1. Manually add three backticks on a new line above your code and on a new line after your code. Note that a backtick is NOT the same as a single quote('). To find the backtick key on your keyboard, see this post.

To see changes to your post as you make them, you can click the (M+) button on the toolbar to bring up the rich text editor:

Happy coding

const generateElement = () => {
  return Math.floor(Math.random() * 100) + 1;
};

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

const generateContainer = () => {
  return document.createElement("div");
};

const fillArrContainer = (containerElement, intArray) => {
  containerElement.innerHTML = "";
  for (let i = 0; i < 5; i++) {
    const span = document.createElement("span");
    span.textContent = intArray[i];
    containerElement.appendChild(span);
  }
};

const isOrdered = (num1, num2) => {
  return num1 <= num2;
};

const swapElements = (intArray, index) => {
  if (!isOrdered(intArray[index], intArray[index + 1])) {
    [intArray[index], intArray[index + 1]] = [
      intArray[index + 1],
      intArray[index],
    ];
    return true;
  }
  return false;
};

const highlightCurrentEls = (element, index) => {
  const children = element.children;
  if (children[index]) {
    children[index].style.border = "2px dashed red";
  }
  if (children[index + 1]) {
    children[index + 1].style.border = "2px dashed red";
  }
};

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

generateBtn.addEventListener("click", () => {
  Array.from(arrayContainer.children).forEach((child) => {
    if (child !== startingArray) child.remove();
  });

  const randomArray = generateArray();
  fillArrContainer(startingArray, randomArray);
});

sortBtn.addEventListener("click", () => {
  Array.from(arrayContainer.children).forEach((child) => {
    if (child !== startingArray) child.remove();
  });

  const spans = startingArray.querySelectorAll("span");
  const arr = Array.from(spans, (span) => Number(span.textContent));

  highlightCurrentEls(startingArray, 0);

  let isFirstComparison = true;
  let swapped;

  do {
    swapped = false;

    for (let j = 0; j < arr.length - 1; j++) {
      if (isFirstComparison) {
        isFirstComparison = false;
      } else {
        const stepContainer = generateContainer();
        fillArrContainer(stepContainer, arr);
        highlightCurrentEls(stepContainer, j);
        arrayContainer.appendChild(stepContainer);
      }

      if (swapElements(arr, j)) swapped = true;
    }
  } while (swapped);
});

I’ve tried getting some help with AI, and managed to resolve the test no 19, and 20, whoever the test no.18 is still failng.

It looks like you may have overlooked this instruction:

The algorithm stops after one cycle completes with no swaps.

There should also be a div showing the final sorted array (see the example app).

Hope that helps.

Just like you suggested, I’ve tried replicating the example project the code is stop when the array is sorted and the final result is shown in the array outlined with green borders, but the test no.18 is somehow still failing, and on top of that the test no.20 (which is previously passing), is now failing.

const generateElement = () => {
  return Math.floor(Math.random() * 100) + 1;
};

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

const generateContainer = () => {
  return document.createElement("div");
};

const fillArrContainer = (containerElement, intArray) => {
  containerElement.innerHTML = "";
  for (let i = 0; i < 5; i++) {
    const span = document.createElement("span");
    span.textContent = intArray[i];
    containerElement.appendChild(span);
  }
};

const isOrdered = (num1, num2) => {
  return num1 <= num2;
};

const isArraySorted = (intArray) => {
  for (let i = 0; i < intArray.length - 1; i++) {
    if (!isOrdered(intArray[i], intArray[i + 1])) return false;
  }
  return true;
};

const swapElements = (intArray, index) => {
  if (!isOrdered(intArray[index], intArray[index + 1])) {
    [intArray[index], intArray[index + 1]] = [
      intArray[index + 1],
      intArray[index],
    ];
    return true;
  }
  return false;
};

const highlightCurrentEls = (element, index) => {
  const children = element.children;
  if (children[index]) {
    children[index].style.border = "2px dashed red";
  }
  if (children[index + 1]) {
    children[index + 1].style.border = "2px dashed red";
  }
};

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

generateBtn.addEventListener("click", () => {
  Array.from(arrayContainer.children).forEach((child) => {
    if (child !== startingArray) child.remove();
  });
  const randomArray = generateArray();
  fillArrContainer(startingArray, randomArray);
});

sortBtn.addEventListener("click", () => {
  Array.from(arrayContainer.children).forEach((child) => {
    if (child !== startingArray) child.remove();
  });

  const spans = startingArray.querySelectorAll("span");
  const arr = Array.from(spans, (span) => Number(span.textContent));

  highlightCurrentEls(startingArray, 0);

  let isFirstComparison = true;
  let sorted = isArraySorted(arr);

  while (!sorted) {
    for (let j = 0; j < arr.length - 1; j++) {
      if (isFirstComparison) {
        isFirstComparison = false;
      } else {
        const stepContainer = generateContainer();
        fillArrContainer(stepContainer, arr);
        highlightCurrentEls(stepContainer, j);
        arrayContainer.appendChild(stepContainer);
      }
      swapElements(arr, j);

      if (isArraySorted(arr)) {
        sorted = true;
        break;
      }
    }
  }

  const finalContainer = generateContainer();
  fillArrContainer(finalContainer, arr);
  finalContainer.style.border = "2px solid green";
  arrayContainer.appendChild(finalContainer);
});

can you please show me your entire solution this one problem is bugging me literally for months now.

It’s against forum rules to provide solutions, but I can still guide you.

Your code is now stopping before it should. The swap of 2 and 16 happens in the fourth iteration of the outer loop. That iteration should complete. And, because there was a swap in that iteration, there should be another complete (fifth) iteration with no swaps before the bubble sort stops and generates the final div.

Hope that helps.

const generateElement = () => {
  return Math.floor(Math.random() * 100) + 1;
};

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

const generateContainer = () => {
  const container = document.createElement("div");
  container.classList.add("array-row");
  return container;
};

const fillArrContainer = (containerElement, intArray) => {
  containerElement.innerHTML = "";
  for (let i = 0; i < 5; i++) {
    const span = document.createElement("span");
    span.textContent = intArray[i];
    containerElement.appendChild(span);
  }
};

const isOrdered = (num1, num2) => {
  return num1 <= num2;
};

const isArraySorted = (intArray) => {
  for (let i = 0; i < intArray.length - 1; i++) {
    if (!isOrdered(intArray[i], intArray[i + 1])) return false;
  }
  return true;
};

const swapElements = (intArray, index) => {
  if (!isOrdered(intArray[index], intArray[index + 1])) {
    [intArray[index], intArray[index + 1]] = [
      intArray[index + 1],
      intArray[index],
    ];
    return true;
  }
  return false;
};

const highlightCurrentEls = (element, index) => {
  const children = element.children;
  if (children[index]) {
    children[index].style.border = "2px dashed red";
  }
  if (children[index + 1]) {
    children[index + 1].style.border = "2px dashed red";
  }
};

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

generateBtn.addEventListener("click", () => {
  Array.from(arrayContainer.children).forEach((child) => {
    if (child !== startingArray) child.remove();
  });
  const randomArray = generateArray();
  fillArrContainer(startingArray, randomArray);
});

sortBtn.addEventListener("click", () => {
  Array.from(arrayContainer.children).forEach((child) => {
    if (child !== startingArray) child.remove();
  });

  const spans = startingArray.querySelectorAll("span");
  const arr = Array.from(spans, (span) => Number(span.textContent));

  highlightCurrentEls(startingArray, 0);

  let isFirstComparison = true;
  let sorted = isArraySorted(arr);

  while (!sorted) {
    for (let j = 0; j < arr.length - 1; j++) {
      if (isFirstComparison) {
        isFirstComparison = false;
      } else {
        const stepContainer = generateContainer();
        fillArrContainer(stepContainer, arr);
        highlightCurrentEls(stepContainer, j);
        arrayContainer.appendChild(stepContainer);
      }
      swapElements(arr, j);

      if (isArraySorted(arr)) {
        const finalStepContainer = generateContainer();
        fillArrContainer(finalStepContainer, arr);
        highlightCurrentEls(finalStepContainer, j);
        arrayContainer.appendChild(finalStepContainer);

        sorted = true;
        break;
      }
    }
  }

  const finalContainer = generateContainer();
  fillArrContainer(finalContainer, arr);
  finalContainer.style.border = "2px solid green";
  arrayContainer.appendChild(finalContainer);
});

I’ve completed the loop, now the array is sorted without any duplicate or redundant attempt, and then printed the final result, but the test no.18, and 20 still failing,

Where in the instructions were you asked to do that?

Here’s a comparison of the result generated by example app and the result generated by your code —

Example app:


Your code: