Build a Sorting Visualizer - Build a Sorting Visualizer

Tell us what’s happening:

I hope this finds you well. I noticed the instructions say that the HTML and CSS are already provided, and the focus should be on completing the Bubble Sort Visualizer with JavaScript. Could you please confirm if my focus should be on JavaScript only?

Also, I often get stuck on test 18 and 19 and would really appreciate your guidance.

Your code so far

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

/* file: styles.css */

/* file: script.js */


function generateElement() {
  return Math.floor(Math.random() * 100) + 1;
}


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


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


function fillArrContainer(container, arr) {
  container.innerHTML = '';
  arr.forEach(n => {
    const s = document.createElement('span');
    s.textContent = n;
    container.appendChild(s);
  });
}


function isOrdered(a, b) {
  return a <= b;
}


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


function highlightCurrentEls(container, index) {
  const spans = container.querySelectorAll('span');
  if (spans[index]) spans[index].style.border = '2px dashed red';
  if (spans[index + 1]) spans[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 startingArrayDiv = document.getElementById('starting-array');

let currentArray = [];


generateBtn.addEventListener('click', () => {
  currentArray = generateArray();
  fillArrContainer(startingArrayDiv, currentArray);
  highlightCurrentEls(startingArrayDiv, 0);


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


sortBtn.addEventListener('click', () => {
  if (!currentArray || currentArray.length === 0) return;

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

 
  fillArrContainer(startingArrayDiv, currentArray);
  highlightCurrentEls(startingArrayDiv, 0);


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

  for (let pass = 0; pass < n - 1; pass++) {
    for (let j = 0; j < n - pass - 1; j++) {

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


      const needSwap = !isOrdered(arr[j], arr[j + 1]);
      if (needSwap) {
        swapElements(arr, j);
        
        const afterDiv = generateContainer();
        fillArrContainer(afterDiv, arr);
        highlightCurrentEls(afterDiv, j);
        arrayContainer.appendChild(afterDiv);
      }
    }
  }


  const finalDiv = generateContainer();
  fillArrContainer(finalDiv, arr);
  arrayContainer.appendChild(finalDiv);

  fillArrContainer(startingArrayDiv, currentArray);
  highlightCurrentEls(startingArrayDiv, 0);
});


Your browser information:

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

Challenge Information:

Build a Sorting Visualizer - Build a Sorting Visualizer

you can check the html and see if you think if anything is missing, but if there is written that you should take it as part of the instructions

Thank you so much for your advice. My question is, how can I ensure all the tests pass, especially 18 and 19?

what are you asking about? if you run the tests and they succed they pass?

Go to the example app. Generate an array there and sort it, then take a screenshot of the results. Then replace the call to generateArray() in your code with a hard-coded array (only for testing!) that matches the one from your screenshot and compare the results.

Your app isn’t behaving the same way the example app does.

Your app:

See how the same numbers are selected on two rows?

Or how the cycle does not go all the way to the last number?

Here is how the example looks:

Thanks everyone for your time and guidance. I will follow the instructions.

1 Like

If you have a question you can ask in your existing topic.

You do both have the exact same problem. Kind of begs the question where you sourced your algorithms from?

I made some updates to my code and successfully passed Test 19, but I’m still stuck on Test 18. I’ve spent a lot of time on this challenge and can’t figure out what’s going wrong. Any help or insight would be hugely appreciated

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 [
    generateElement(),
    generateElement(),
    generateElement(),
    generateElement(),
    generateElement()
  ];
}

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

function fillArrContainer(htmlEl, arr) {
  htmlEl.innerHTML = `
    <span>${arr[0]}</span>
    <span>${arr[1]}</span>
    <span>${arr[2]}</span>
    <span>${arr[3]}</span>
    <span>${arr[4]}</span>
  `;
}

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";
}

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

sortBtn.addEventListener("click", () => {
  // Clear old sort steps
  while (arrayContainer.children.length > 1) {
    arrayContainer.removeChild(arrayContainer.lastChild);
  }

  // Get current array from DOM
  let currentArr = Array.from(startingArray.children).map(child =>
    Number(child.textContent)
  );

  // Highlight first comparison
  highlightCurrentEls(startingArray, 0);

  // Bubble sort with visual steps
  for (let i = 0; i < currentArr.length - 1; i++) {
    let swapped = false;

    for (let j = 0; j < currentArr.length - 1 - i; j++) {
      // Swap if needed
      if (currentArr[j] > currentArr[j + 1]) {
        swapElements(currentArr, j);
        swapped = true;
      }

      // Render the current state
      let newContainer = generateContainer();
      fillArrContainer(newContainer, currentArr);
      highlightCurrentEls(newContainer, j);
      arrayContainer.appendChild(newContainer);
    }

    if (!swapped) break;
  }

  // Final sorted array container
  let lastContainer = generateContainer();
  lastContainer.style.border = "4px solid green";
  fillArrContainer(lastContainer, currentArr);
  arrayContainer.appendChild(lastContainer);
});




















































































































What is test 18?

What have you done to investigate?

Did you correct your algorithm to work the same way as the example?

Does your algo work like this?

When the last element of the sequence is reached, it starts a new cycle from the beginning of the sequence, and repeats the process until the elements are sorted. The algorithm stops after one cycle completes with no swaps.

If you need further assistance can you share a screenshot of your sorted array?

Thanks, this has been one of the toughest projects for me, and I couldn’t quite get the algorithm to work like the example.

you should not use the optimized bubble sort, you keep using that

Is there something that you need help with?

Do you have a question about any of the code you’ve written?

Open a new forum topic.

If you have a question about a specific challenge as it relates to your written code for that challenge and need some help, click the Help button located on the challenge. This button only appears if you have tried to submit an answer at least three times.

The Help button will create a new topic with all code you have written and include a link to the challenge also. You will still be able to ask any questions in the post before submitting it to the forum.

Thank you.

Inside your actual bubble sort, console.log() the values of i and j. Is that what they should be to sort through an array of 5 elements?