Problems with Step 18, Build a Sorting Visualizer, Certified Full Stack Developer Curriculum

Hi, I can’t pass the test 18 ( Certified Full Stack Developer Curriculum) and I don’t know why; could someone help me to fix this issue and complete the project ?

    1. 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.
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(container, arr) {
  container.innerHTML = ""; // Clear existing content
  arr.forEach(num => {
    const span = document.createElement("span");
    span.textContent = num;
    container.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(container, index) {
  const children = container.children;
  if (index < children.length) {
    children[index].style.border = "2px dashed red";
  }
  if (index + 1 < children.length) {
    children[index + 1].style.border = "2px dashed red";
  }
}

document.getElementById("generate-btn").addEventListener("click", function () {
  const arrayContainer = document.getElementById("array-container");
  arrayContainer.innerHTML = "";

  const startingArrayDiv = document.createElement("div");
  startingArrayDiv.id = "starting-array";
  arrayContainer.appendChild(startingArrayDiv);

  currentArray = generateArray();
  fillArrContainer(startingArrayDiv, currentArray);
});

document.getElementById("sort-btn").addEventListener("click", function () {
  if (currentArray.length === 0) return;
  const arrayContainer = document.getElementById("array-container");

  const startingArrayDiv = document.getElementById("starting-array");
  fillArrContainer(startingArrayDiv, currentArray);
  highlightCurrentEls(startingArrayDiv, 0);
  
  let arr = currentArray.slice();
  const n = arr.length;
  let comparisonCount = 0; // total comparisons performed

  for (let i = 0; i < n - 1; i++) {
    for (let j = 0; j < n - i - 1; j++) {
      comparisonCount++;
      if (comparisonCount === 1) {
        if (!isOrdered(arr[j], arr[j + 1])) {
          swapElements(arr, j);
        }
      } else {
        const stepContainer = generateContainer();
        fillArrContainer(stepContainer, arr);
        highlightCurrentEls(stepContainer, j);
        arrayContainer.appendChild(stepContainer);

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

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

Here is my Javascript Code.

Thanks in advance for the replies !!

Can you please provide a link to the project for context?

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.

https://www.freecodecamp.org/learn/full-stack-developer/lab-sorting-visualizer/build-a-sorting-visualizer

I tried in different ways to solve this step, but I think it’s actually a bug on your site.

console.log(arrayContainer.innerHTML)

1. <div id="starting-array"><span style="border: 2px dashed red;">70</span><span style="border: 2px dashed red;">79</span><span>98</span><span>81</span><span>10</span></div>
2. <div><span>70</span><span style="border: 2px dashed red;">79</span><span style="border: 2px dashed red;">98</span><span>81</span><span>10</span></div>
3. <div><span>70</span><span>79</span><span style="border: 2px dashed red;">98</span><span style="border: 2px dashed red;">81</span><span>10</span></div>
4. <div><span>70</span><span>79</span><span>81</span><span style="border: 2px dashed red;">98</span><span style="border: 2px dashed red;">10</span></div>
5. <div><span style="border: 2px dashed red;">70</span><span style="border: 2px dashed red;">79</span><span>81</span><span>10</span><span>98</span></div>
6. <div><span>70</span><span style="border: 2px dashed red;">79</span><span style="border: 2px dashed red;">81</span><span>10</span><span>98</span></div>
7. <div><span>70</span><span>79</span><span style="border: 2px dashed red;">81</span><span style="border: 2px dashed red;">10</span><span>98</span></div>
8. <div><span style="border: 2px dashed red;">70</span><span style="border: 2px dashed red;">79</span><span>10</span><span>81</span><span>98</span></div>
9. <div><span>70</span><span style="border: 2px dashed red;">79</span><span style="border: 2px dashed red;">10</span><span>81</span><span>98</span></div>
10. <div><span style="border: 2px dashed red;">70</span><span style="border: 2px dashed red;">10</span><span>79</span><span>81</span><span>98</span></div>
11. <div><span>10</span><span>70</span><span>79</span><span>81</span><span>98</span></div>

It does seem to have 11 div including the first and last.

and how many divs should it contain?

11 as far as I can tell. Not sure what else to check here.

I’ve opened an issue here: https://github.com/freeCodeCamp/freeCodeCamp/issues/59089

One strange thing is that it always seems to take exactly 11 steps. When I run the tests it’s all 11 steps except one which is 21

Maybe this is a clue, you have 11 divs here, but it seemed to only take 10 steps:

The last div here seems unnecessary. I think this might be it. I thought it was strange it always took exactly 11 steps.

I guess it depends if a comparison without a swap counts as a “Step” or only when numbers are swapped? Really not sure…

If I pass your algorithm a sorted array it still takes 11 steps.

Not sure if it should be this way or not yet

"These passes through the list are repeated until no swaps have to be performed during a pass, meaning that the list has become fully sorted. https://en.wikipedia.org/wiki/Bubble_sort

It seems like if it makes it to the end with no swaps, it should be done.

it doesn’t work in any way, in my opinion it’s actually a bug on the freeCodeCamp page.

do you have a version in which your code does not skip comarisons? in which it is not optimized?

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(container, arr) {
  container.innerHTML = "" // Clear existing content
  arr.forEach((num) => {
    const span = document.createElement("span")
    span.textContent = num
    container.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(container, index) {
  const children = container.children
  if (index < children.length) {
    children[index].style.border = "2px dashed red"
  }
  if (index + 1 < children.length) {
    children[index + 1].style.border = "2px dashed red"
  }
}

document.getElementById("generate-btn").addEventListener("click", () => {
  const arrayContainer = document.getElementById("array-container")
  arrayContainer.innerHTML = ""

  const startingArrayDiv = document.createElement("div")
  startingArrayDiv.id = "starting-array"
  arrayContainer.appendChild(startingArrayDiv)

  currentArray = generateArray()
  fillArrContainer(startingArrayDiv, currentArray)
})

document.getElementById("sort-btn").addEventListener("click", () => {
  if (currentArray.length === 0) return
  const arrayContainer = document.getElementById("array-container")

  const startingArrayDiv = document.getElementById("starting-array")
  fillArrContainer(startingArrayDiv, currentArray)
  highlightCurrentEls(startingArrayDiv, 0)

  const arr = currentArray.slice()
  const n = arr.length
  let comparisonCount = 0 

  for (let i = 0; i < n - 1; i++) {
    for (let j = 0; j < n - i - 1; j++) {
      comparisonCount++
      if (comparisonCount === 1) {
        if (!isOrdered(arr[j], arr[j + 1])) {
          swapElements(arr, j)
        }
      } else {
        const stepContainer = generateContainer()
        fillArrContainer(stepContainer, arr)
        highlightCurrentEls(stepContainer, j)
        arrayContainer.appendChild(stepContainer)
        if (!isOrdered(arr[j], arr[j + 1])) {
          swapElements(arr, j)
        }
      }
    }
  }

  const finalContainer = generateContainer()
  fillArrContainer(finalContainer, arr)
  arrayContainer.appendChild(finalContainer)
})


Here is the original code without optimization.

that is still skipping comparisons

image

here it is missing the 7-77 comparion

ok, can you help me to solve this problem ?

you need to not skip comparisons, which part of your code deals with selecting to items in the array to compare?

1 Like
for (let i = 0; i < n - 1; i++) {
  for (let j = 0; j < n - i - 1; j++) {
    if (i === 0 && j === 0) continue;

    const stepDiv = document.createElement("div");
    fillArrContainer(stepDiv, arr);
    highlightCurrentEls(stepDiv, j);
    arrayContainer.appendChild(stepDiv);
    stepCount++;
    swapElements(arr, j);
  }
}

This is the part of the code that deals with selecting items to compare.

do you understand what this does?

This condition controls how many comparisons we make in each pass of the bubble sort:

  • n is the length of the array
  • i is the current pass number (starting from 0)
  • After each pass, the largest i+1 elements are already in their correct positions at the end of the array
  • So we only need to compare elements up to index n - i - 2 with the next element (at index n - i - 1)
  • That’s why the condition is j < n - i - 1

For example, in a 5-element array:

  • In the first pass (i=0), we compare elements at indices 0,1,2,3 with the next element (j goes from 0 to 3)
  • In the second pass (i=1), we compare elements at indices 0,1,2 with the next element (j goes from 0 to 2)
  • In the third pass (i=2), we compare elements at indices 0,1 with the next element (j goes from 0 to 1)
  • In the fourth pass (i=3), we compare the element at index 0 with the next element (j goes from 0 to 0)

This ensures that we don’t make unnecessary comparisons with elements that are already in their correct positions at the end of the array after each pass.

Did the instructions ask you to remove any comparisons?

This looks like an explanation might be written by AI. If so, I wouldn’t use AI to write your algorithms or explain your code to you.