Build a Sorting Visualizer - Build a Sorting Visualizer

Tell us what’s happening:

My sorting visualizer code has problem on 15, 18, and 19. I need help, please. 15. Your highlightCurrentEls function should give the descendants of the specified element, located at the given index and the next index, a border that is dashed, red, and set to a width of your choice.
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

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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36

Challenge Information:

Build a Sorting Visualizer - Build a Sorting Visualizer

const generateBtn = document.getElementById("generate-btn");

const sortBtn = document.getElementById("sort-btn");

const arrayContainer = document.getElementById("array-container");

const startingArrayEl = document.getElementById("starting-array");



let currentArray = \[\];




function generateElement() {

  return Math.floor(Math.random() \* 100) + 1;

}




function generateArray() {

  const arr = \[\];

  for (let i = 0; i < 5; i++) arr.push(generateElement());

  return arr;

}




function generateContainer() {

  return document.createElement("div");

}




function fillArrContainer(element, arr) {

  element.innerHTML = "";

  arr.forEach(num => {

    const span = document.createElement("span");

    span.textContent = num;

    element.appendChild(span);

  });

}




function isOrdered(a, b) {

  return a <= b;

}




function swapElements(arr, index) {

  if (!isOrdered(arr\[index\], arr\[index + 1\])) {

    const temp = arr\[index\];

    arr\[index\] = arr\[index + 1\];

    arr\[index + 1\] = temp;

  }

}




function highlightCurrentEls(element, index) {

  const children = element.children;

  if (children\[index\] && children\[index + 1\]) {

    children\[index\].style.borderStyle = "dashed";

    children\[index\].style.borderColor = "red";

    children\[index\].style.borderWidth = "3px";



    children\[index + 1\].style.borderStyle = "dashed";

    children\[index + 1\].style.borderColor = "red";

    children\[index + 1\].style.borderWidth = "3px";

  }

}




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

  currentArray = generateArray();



  

  arrayContainer.innerHTML = "";

  arrayContainer.appendChild(startingArrayEl);



  

  fillArrContainer(startingArrayEl, currentArray);

  highlightCurrentEls(startingArrayEl, 0);

});




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

  if (currentArray.length === 0) return;



  const arr = \[...currentArray\];

  const n = arr.length;



  

  arrayContainer.innerHTML = "";

  arrayContainer.appendChild(startingArrayEl);

  fillArrContainer(startingArrayEl, arr);

  highlightCurrentEls(startingArrayEl, 0);



  

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

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



      

      const compareDiv = generateContainer();

      fillArrContainer(compareDiv, arr);

      highlightCurrentEls(compareDiv, i);

      arrayContainer.appendChild(compareDiv);



      

      if (!isOrdered(arr\[i\], arr\[i + 1\])) {

        swapElements(arr, i);



        const swapDiv = generateContainer();

        fillArrContainer(swapDiv, arr);

        arrayContainer.appendChild(swapDiv);

      }

    }

  }

});

Can you take a screenshot of your program after it has sorted an array?

Please share your code again but use these instructions to format it

When you enter a code block into a forum post, please precede it with three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add the backticks.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

Please, I have not been able to figure out what the problems on 15, 18 and 19 are. I need help. Thank you.   Sorting Visualization.
Please, still on line 15, 18 and 19; i can't move forward. I need help please.  I have added what is on my console after click on 'generate array.'

Try looking at how the example sorter works. Your highlighting, comparisons and switches should work the same way.

Your highlighting/comparison skips a line?

// ================= REQUIRED FUNCTIONS =================

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

function generateArray() {
  const arr = [];
  for (let i = 0; i < 5; i++) {
    arr.push(generateElement());
  }
  return arr;
}

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

function fillArrContainer(element, array) {
  element.innerHTML = "";
  array.forEach((num) => {
    const span = document.createElement("span");
    span.textContent = num;
    element.appendChild(span);
  });
}

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

function swapElements(arr, index) {
  if (arr[index] > arr[index + 1]) {
    [arr[index], arr[index + 1]] = [arr[index + 1], arr[index]];
  }
}

function highlightCurrentEls(element, index) {
  Array.from(element.children).forEach((child) => (child.style.border = "none"));
  if (element.children[index] && element.children[index + 1]) {
    element.children[index].style.border = "2px dashed red";
    element.children[index + 1].style.border = "2px dashed red";
  }
}

// ================= DOM ELEMENTS =================

const generateBtn = document.getElementById("generate-btn");
const sortBtn = document.getElementById("sort-btn");
const arrayContainer = document.getElementById("array-container");
const startingArrayDiv = document.getElementById("starting-array"); // Make sure this exists in HTML

let currentArray = [];

// ================= GENERATE ARRAY =================

generateBtn.addEventListener("click", () => {
  arrayContainer.innerHTML = "";
  currentArray = generateArray();
  fillArrContainer(startingArrayDiv, currentArray);
  arrayContainer.appendChild(startingArrayDiv.cloneNode(true));
});

// ================= SORT ARRAY =================

sortBtn.addEventListener("click", () => {
  if (currentArray.length !== 5) return;

  arrayContainer.innerHTML = "";

  let arr = [...currentArray];

  // STEP 1: Starting row with first two highlighted (index 0)
  fillArrContainer(startingArrayDiv, arr);
  highlightCurrentEls(startingArrayDiv, 0);
  arrayContainer.appendChild(startingArrayDiv);

  let workingArray = [...arr];
  
  // Track all steps
  let steps = [];
  
  // Pass 1: 4 comparisons - highlights at 0,1,2,3
  for (let i = 0; i < 4; i++) {
    steps.push({
      array: [...workingArray],
      highlightIndex: i
    });
    
    if (workingArray[i] > workingArray[i + 1]) {
      let temp = workingArray[i];
      workingArray[i] = workingArray[i + 1];
      workingArray[i + 1] = temp;
    }
  }
  
  // Pass 2: 3 comparisons - highlights at 0,1,2 (reset to 0)
  for (let i = 0; i < 3; i++) {
    steps.push({
      array: [...workingArray],
      highlightIndex: i
    });
    
    if (workingArray[i] > workingArray[i + 1]) {
      let temp = workingArray[i];
      workingArray[i] = workingArray[i + 1];
      workingArray[i + 1] = temp;
    }
  }
  
  // Pass 3: 2 comparisons - highlights at 0,1 (reset to 0)
  for (let i = 0; i < 2; i++) {
    steps.push({
      array: [...workingArray],
      highlightIndex: i
    });
    
    if (workingArray[i] > workingArray[i + 1]) {
      let temp = workingArray[i];
      workingArray[i] = workingArray[i + 1];
      workingArray[i + 1] = temp;
    }
  }
  
  // Pass 4: 1 comparison - highlight at 0
  for (let i = 0; i < 1; i++) {
    steps.push({
      array: [...workingArray],
      highlightIndex: i
    });
    
    if (workingArray[i] > workingArray[i + 1]) {
      let temp = workingArray[i];
      workingArray[i] = workingArray[i + 1];
      workingArray[i + 1] = temp;
    }
  }
  
  // Add all 10 comparison steps to container
  steps.forEach((step) => {
    const stepDiv = generateContainer();
    fillArrContainer(stepDiv, step.array);
    highlightCurrentEls(stepDiv, step.highlightIndex);
    arrayContainer.appendChild(stepDiv);
  });

  // STEP 12: Extra full pass row (one more complete pass with highlights at 0,1,2,3)
  // This shows the array is fully sorted by doing one more pass
  const extraPassDiv1 = generateContainer();
  fillArrContainer(extraPassDiv1, workingArray);
  highlightCurrentEls(extraPassDiv1, 0);
  arrayContainer.appendChild(extraPassDiv1);
  
  const extraPassDiv2 = generateContainer();
  fillArrContainer(extraPassDiv2, workingArray);
  highlightCurrentEls(extraPassDiv2, 1);
  arrayContainer.appendChild(extraPassDiv2);
  
  const extraPassDiv3 = generateContainer();
  fillArrContainer(extraPassDiv3, workingArray);
  highlightCurrentEls(extraPassDiv3, 2);
  arrayContainer.appendChild(extraPassDiv3);
  
  const extraPassDiv4 = generateContainer();
  fillArrContainer(extraPassDiv4, workingArray);
  highlightCurrentEls(extraPassDiv4, 3);
  arrayContainer.appendChild(extraPassDiv4);

  // STEP 13: Final sorted array (green row - no highlight)
  const finalDiv = generateContainer();
  fillArrContainer(finalDiv, workingArray);
  arrayContainer.appendChild(finalDiv);

  console.log("Total steps:", arrayContainer.children.length);
  console.log("Sequence:", Array.from(arrayContainer.children).map(div => 
    Array.from(div.children).map(span => span.textContent).join(' ')
  ));
  
  console.log("Highlights:", Array.from(arrayContainer.children).map((div, index) => {
    const children = div.children;
    for (let i = 0; i < children.length; i++) {
      if (children[i].style.border && children[i].style.border.includes("red")) {
        return i;
      }
    }
    return "none";
  }).join(' '));
});

??

Please Tell us what’s happening in your own words.

Learning to describe problems is hard, but it is an important part of learning how to code.

Also, the more you say, the more we can help!

Tell us what’s happening:

//failed this
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.
//My output: //Output: Total steps: 12
First child is startingArrayDiv: true
Sequence: [ ‘18 10 69 32 22’,
‘10 18 69 32 22’,
‘10 18 69 32 22’,
‘10 18 32 69 22’,
‘10 18 32 22 69’,
‘10 18 32 22 69’,
'10 18

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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36

Challenge Information:

Build a Sorting Visualizer - Build a Sorting Visualizer

Hey there,

Please update the message to include your code. The code was too long to be automatically inserted by the help button.

When you enter a code, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

// ================= SORT ARRAY =================
sortBtn.addEventListener("click", () => {
  if (currentArray.length !== 5) return;

  
  arrayContainer.innerHTML = "";

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

  
  fillArrContainer(startingArrayDiv, arr);
  highlightCurrentEls(startingArrayDiv, 0);
  arrayContainer.appendChild(startingArrayDiv.cloneNode(true));

  let stepCount = 1; 
  for (let pass = 0; pass < n - 1; pass++) {
    for (let i = 0; i < n - 1; i++) {
      if (stepCount >= 11) break; 
      const stepDiv = generateContainer();
      fillArrContainer(stepDiv, arr);
      highlightCurrentEls(stepDiv, i);
      arrayContainer.appendChild(stepDiv);
      stepCount++;

      // Swap if needed
      if (!isOrdered(arr[i], arr[i + 1])) {
        swapElements(arr, i);
      }
    }
  }

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

  
  console.log("Total steps:", arrayContainer.children.length);
  console.log(
    "Sequence:",
    Array.from(arrayContainer.children).map((div) =>
      Array.from(div.children).map((span) => span.textContent).join(" ")
    )
  );
});

I am not able to use your code, it errors out with Uncaught ReferenceError: sortBtn is not defined

I have merged your two topics, please do not create duplicate topics for the same challenge

  1. Step Count Discrepancy

  • I don’t know how many steps i am suposed to generate in total, is FCC actually expecting 12 or 13 steps total:

    • 1 starting row (highlighted)

    • 10 comparison rows (4+3+2+1)

    • 1 extra full pass row (showing one more complete pass)

    • 1 final sorted row (green)

  1. I have Inconsistent Highlight Patterns: I am thinking that FCC expects a specific highlight sequence: 0,1,2,3,0,1,2,0,1,0 for the 10 comparison steps; but my implementations kept resetting to the wrong indices or continuing the pattern incorrectly.
  2. Timing of Container Creation vs. Swaps

    • Iam struggling with whether to show the array state BEFORE or AFTER each comparison

    • The correct approach: Create container and highlight FIRST, THEN perform the swap

And sometimes line 18 will pass and failed 19; and 19 will passed and failed 18.


//This my code again//



// ================= REQUIRED FUNCTIONS =================

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

function generateArray() {
  const arr = [];
  for (let i = 0; i < 5; i++) {
    arr.push(generateElement());
  }
  return arr;
}

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

function fillArrContainer(element, array) {
  element.innerHTML = "";
  array.forEach((num) => {
    const span = document.createElement("span");
    span.textContent = num;
    element.appendChild(span);
  });
}

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

function swapElements(arr, index) {
  if (arr[index] > arr[index + 1]) {
    [arr[index], arr[index + 1]] = [arr[index + 1], arr[index]];
  }
}

function highlightCurrentEls(element, index) {
  Array.from(element.children).forEach((child) => (child.style.border = "none"));
  if (element.children[index] && element.children[index + 1]) {
    element.children[index].style.border = "2px dashed red";
    element.children[index + 1].style.border = "2px dashed red";
  }
}

// ================= DOM ELEMENTS =================

const generateBtn = document.getElementById("generate-btn");
const sortBtn = document.getElementById("sort-btn");
const arrayContainer = document.getElementById("array-container");
const startingArrayDiv = document.getElementById("starting-array"); // Make sure this exists in HTML

let currentArray = [];

// ================= GENERATE ARRAY =================

generateBtn.addEventListener("click", () => {
  arrayContainer.innerHTML = "";
  currentArray = generateArray();
  fillArrContainer(startingArrayDiv, currentArray);
  arrayContainer.appendChild(startingArrayDiv.cloneNode(true));
});

// ================= SORT ARRAY =================

sortBtn.addEventListener("click", () => {
  if (currentArray.length !== 5) return;

  arrayContainer.innerHTML = "";

  let arr = [...currentArray];

  // STEP 1: Starting row with first two highlighted (index 0)
  fillArrContainer(startingArrayDiv, arr);
  highlightCurrentEls(startingArrayDiv, 0);
  arrayContainer.appendChild(startingArrayDiv);

  let workingArray = [...arr];
  
  // Track all steps
  let steps = [];
  
  // Pass 1: 4 comparisons - highlights at 0,1,2,3
  for (let i = 0; i < 4; i++) {
    steps.push({
      array: [...workingArray],
      highlightIndex: i
    });
    
    if (workingArray[i] > workingArray[i + 1]) {
      let temp = workingArray[i];
      workingArray[i] = workingArray[i + 1];
      workingArray[i + 1] = temp;
    }
  }
  
  // Pass 2: 3 comparisons - highlights at 0,1,2 (reset to 0)
  for (let i = 0; i < 3; i++) {
    steps.push({
      array: [...workingArray],
      highlightIndex: i
    });
    
    if (workingArray[i] > workingArray[i + 1]) {
      let temp = workingArray[i];
      workingArray[i] = workingArray[i + 1];
      workingArray[i + 1] = temp;
    }
  }
  
  // Pass 3: 2 comparisons - highlights at 0,1 (reset to 0)
  for (let i = 0; i < 2; i++) {
    steps.push({
      array: [...workingArray],
      highlightIndex: i
    });
    
    if (workingArray[i] > workingArray[i + 1]) {
      let temp = workingArray[i];
      workingArray[i] = workingArray[i + 1];
      workingArray[i + 1] = temp;
    }
  }
  
  // Pass 4: 1 comparison - highlight at 0
  for (let i = 0; i < 1; i++) {
    steps.push({
      array: [...workingArray],
      highlightIndex: i
    });
    
    if (workingArray[i] > workingArray[i + 1]) {
      let temp = workingArray[i];
      workingArray[i] = workingArray[i + 1];
      workingArray[i + 1] = temp;
    }
  }
  
  // Add all 10 comparison steps to container
  steps.forEach((step) => {
    const stepDiv = generateContainer();
    fillArrContainer(stepDiv, step.array);
    highlightCurrentEls(stepDiv, step.highlightIndex);
    arrayContainer.appendChild(stepDiv);
  });

  // STEP 12: Extra full pass row (one more complete pass with highlights at 0,1,2,3)
  // This shows the array is fully sorted by doing one more pass
  const extraPassDiv1 = generateContainer();
  fillArrContainer(extraPassDiv1, workingArray);
  highlightCurrentEls(extraPassDiv1, 0);
  arrayContainer.appendChild(extraPassDiv1);
  
  const extraPassDiv2 = generateContainer();
  fillArrContainer(extraPassDiv2, workingArray);
  highlightCurrentEls(extraPassDiv2, 1);
  arrayContainer.appendChild(extraPassDiv2);
  
  const extraPassDiv3 = generateContainer();
  fillArrContainer(extraPassDiv3, workingArray);
  highlightCurrentEls(extraPassDiv3, 2);
  arrayContainer.appendChild(extraPassDiv3);
  
  const extraPassDiv4 = generateContainer();
  fillArrContainer(extraPassDiv4, workingArray);
  highlightCurrentEls(extraPassDiv4, 3);
  arrayContainer.appendChild(extraPassDiv4);

  // STEP 13: Final sorted array (green row - no highlight)
  const finalDiv = generateContainer();
  fillArrContainer(finalDiv, workingArray);
  arrayContainer.appendChild(finalDiv);

  console.log("Total steps:", arrayContainer.children.length);
  console.log("Sequence:", Array.from(arrayContainer.children).map(div => 
    Array.from(div.children).map(span => span.textContent).join(' ')
  ));
  
  console.log("Highlights:", Array.from(arrayContainer.children).map((div, index) => {
    const children = div.children;
    for (let i = 0; i < children.length; i++) {
      if (children[i].style.border && children[i].style.border.includes("red")) {
        return i;
      }
    }
    return "none";
  }).join(' '));
});

Questions for clarificatio, please:
“The Bubble Sort Visualizer and have passed all tests except 18 and 19. Using, a sample image from FCC, I’ve confirmed we need 13 total steps (1 initial + 10 comparisons + 1 extra pass + 1 final); but i don’t know if i’m right with the assumption.
My highlight pattern is 0,1,2,3,0,1,2,0,1,0 for the 10 comparisons, followed by an extra pass with highlight 0, then final with no highlight. But tests still fail. Please, may I know the EXACT expected sequence and highlight pattern for a sample array like [5,3,8,4,2]? Also, should the extra pass show all 4 comparisons or just one?”

that’s wrong, the highlight pattern should repeat the same for all the passes, see the example app that does 0,1,2,3,0,1,2,3,0,1,2,3

“For the Bubble Sort Visualizer lab, how many total steps (div elements) should be in #array-container after clicking sort-btn?”

Questions for clarification:

  1. Is it 12 steps? (Initial + 10 comparisons + Final)

  2. Is it 13 steps? (Initial + 10 comparisons + Extra pass + Final)

  3. Is it 16 steps? (Initial + 4+3+2+1+4 comparisons + Final)

  4. Or something else?

  • What is the exact highlight pattern expected?

  • Should the extra pass show all 4 comparisons or just one?