Build a Sorting Visualizer - Build a Sorting Visualizer

Tell us what’s happening:

Step 18 for Build Sorting Visualizer failed and please help me fix it thanks 18. After you click #sort-btn, #array-container should contain as many div elements as the steps required by the Bubble Sort algorithm to sort the starting array, including the div representing the starting array and a div representing the sorted array.

Your code so far

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

/* file: styles.css */

/* file: script.js */
// Generate a random integer between 1 and 100
function generateElement() {
  return Math.floor(Math.random() * 100) + 1;
}

// Generate an array of 5 random integers
function generateArray() {
  const array = [];
  for (let i = 0; i < 5; i++) {
    array.push(generateElement());
  }
  return array;
}

// Create a new <div> container
function generateContainer() {
  return document.createElement("div");
}

// Fill a container with 5 <span> elements
function fillArrContainer(container, arr) {
  container.innerHTML = "";
  arr.forEach(num => {
    const span = document.createElement("span");
    span.textContent = num;
    container.appendChild(span);
  });
}

// Compare two numbers for bubble sort
function isOrdered(a, b) {
  return a <= b;
}

// Swap elements if out of order
function swapElements(arr, index) {
  if (arr[index] > arr[index + 1]) {
    const temp = arr[index];
    arr[index] = arr[index + 1];
    arr[index + 1] = temp;
  }
}

// Highlight two adjacent elements
function highlightCurrentEls(container, index) {
  // Clear previous highlights to keep visuals clean
  Array.from(container.children).forEach(child => {
    child.style.border = "";
  });

  const first = container.children[index];
  const second = container.children[index + 1];

  if (first) first.style.border = "2px dashed red";
  if (second) second.style.border = "2px dashed red";
}

// Record all bubble sort steps
function bubbleSortSteps(arr) {
  const steps = [];
  const a = arr.slice();

  for (let i = 0; i < a.length; i++) {
    for (let j = 0; j < a.length - i - 1; j++) {
      // Record the state before comparing/swapping
      steps.push({ values: a.slice(), index: j });
      if (!isOrdered(a[j], a[j + 1])) {
        swapElements(a, j);
      }
    }
  }

  // Final sorted state
  steps.push({ values: a.slice(), index: -1 });
  return steps;
}

function runBubbleSortVisualization(startingArray, arrayContainer, startingContainer) {
  // Ensure #starting-array is a child of #array-container
  if (startingContainer.parentElement !== arrayContainer) {
    arrayContainer.appendChild(startingContainer);
  }

  // Remove all generated step divs, keep only #starting-array
  const children = Array.from(arrayContainer.children);
  children.forEach(child => {
    if (child !== startingContainer) child.remove();
  });

  // STEP 0: starting array is #starting-array itself
  fillArrContainer(startingContainer, startingArray);
  highlightCurrentEls(startingContainer, 0);

  // Bubble sort steps (includes starting snapshot and final)
  const stepsData = bubbleSortSteps(startingArray);

  // Append all steps except the first (duplicate of starting-array)
  stepsData.forEach((step, idx) => {
    if (idx === 0) return; // skip duplicate starting step

    const div = generateContainer();
    fillArrContainer(div, step.values);

    if (step.index >= 0) {
      highlightCurrentEls(div, step.index);
    }

    arrayContainer.appendChild(div);
  });
}

// DOM setup
document.addEventListener("DOMContentLoaded", () => {
  const generateBtn = document.getElementById("generate-btn");
  const sortBtn = document.getElementById("sort-btn");
  const startingContainer = document.getElementById("starting-array");
  const arrayContainer = document.getElementById("array-container");

  let startingArray = [];

  // Generate button
  generateBtn.addEventListener("click", () => {
    // Keep only #starting-array
    const children = Array.from(arrayContainer.children);
    children.forEach(child => {
      if (child !== startingContainer) child.remove();
    });

    // Ensure #starting-array is in #array-container
    if (startingContainer.parentElement !== arrayContainer) {
      arrayContainer.appendChild(startingContainer);
    }

    // Generate new array
    startingArray = generateArray();
    fillArrContainer(startingContainer, startingArray);
    highlightCurrentEls(startingContainer, 0);
  });

  // Sort button
  sortBtn.addEventListener("click", () => {
    // Ensure #starting-array is inside #array-container
    if (startingContainer.parentElement !== arrayContainer) {
      arrayContainer.appendChild(startingContainer);
    }

    // Remove ONLY step divs, keep #starting-array untouched
    const children = Array.from(arrayContainer.children);
    children.forEach(child => {
      if (child !== startingContainer) child.remove();
    });

    // Read current numbers from #starting-array
    const arr = Array.from(startingContainer.children).map(span => Number(span.textContent));

    // Ensure #starting-array has exactly 5 spans
    fillArrContainer(startingContainer, arr);
    highlightCurrentEls(startingContainer, 0);

    // Run visualization
    runBubbleSortVisualization(arr, arrayContainer, startingContainer);
  });
});

Your browser information:

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

Challenge Information:

Build a Sorting Visualizer - Build a Sorting Visualizer

I see two problems

First is that when I click generate two numbers are already highlighted.

The other is the same as these threads.

https://forum.freecodecamp.org/t/build-a-sorting-visualizer-build-a-sorting-visualizer/770788

https://forum.freecodecamp.org/t/build-a-sorting-visualizer-build-a-sorting-visualizer/770639

https://forum.freecodecamp.org/t/build-a-sorting-visualizer-build-a-sorting-visualizer/769819

https://forum.freecodecamp.org/t/build-a-sorting-visualizer-build-a-sorting-visualizer/769172

hi friend. i have the same trouble . and i take a lot of time ti solve it. an important at 18 is how many step do you make to sort array. so if you use 2 for loop. you can’t reach the right step.

i was fixed my code by use while loop and a coundition is array sorted or not.
like this:

removed

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge. How to Help Someone with Their Code Using the Socratic Method

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.