Build a Sorting Visualizer - Build a Sorting Visualizer

Tell us what’s happening:

I cannot for the life of me figure out why my code isn’t passing Test 20?? My sortBtn eventListener does make use of the highlightCurrentEls function in multiple areas. My program does exactly what the stories ask for. I had to use highlightCurrentEls twice as part of my clean-up logic, and to make sure the #starting-array was utilized as the first step in the bubble sort visualization. Can someone please help!!!

Your code so far

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Sorting Visualizer</title>
    <link rel="stylesheet" href="styles.css">
</head>

<body>
    <main>
        <div id="array-container">
            <div id="starting-array"></div>
        </div>
        <div id="btn-container">
            <button id="generate-btn" type="button">Generate Array</button>
            <button id="sort-btn" type="button">Sort Array</button>
        </div>
    </main>
    <script src="script.js"></script>
</body>

</html>

* {
    box-sizing: border-box;
}

main {
    height: 100vh;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
}

#array-container {
    max-height: 95vh;
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    gap: 2px;

}

#array-container>div {
    min-width: 8rem;
    height: 2rem;
    box-shadow: rgba(50, 50, 93, 0.25) 0px 2px 5px -1px, rgba(0, 0, 0, 0.3) 0px 1px 3px -1px;
    border-radius: 10px;
    margin-bottom: 0.2rem;
    border: 2px solid darkgray;
    display: flex;
    justify-content: space-evenly;
    align-items: center;
}

#starting-array {
    border: 4px solid darkblue !important;
}

#btn-container {
    display: flex;
    justify-content: space-around;
}

button {
    padding: 2px;
    margin: 5px;
}

span {
    border-radius: 2px;
    padding: 0.5px;
    margin: 0
}

@media (min-width: 430px) {
  #array-container>div {
    min-width: 12rem;    
  }
  span {
    padding: 1px;
    margin: 1px;
  }
}

const generateBtn = document.getElementById("generate-btn");
const sortBtn = document.getElementById("sort-btn");
const startArr = document.getElementById("starting-array");
const arrContainer = document.getElementById("array-container");
let currentArray = [];

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

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

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

const fillArrContainer = (container, arr) => {
  arr.forEach(num => {
    const span = document.createElement("span");
    span.textContent = num;
    container.appendChild(span);
  })
}

const isOrdered = (int1, int2) => {
  return int1 <= int2;
}

const swapElements = (arr, index) => {
  let temp = 0;
  if (!isOrdered(arr[index], arr[index + 1])) {
    temp = arr[index];
    arr[index] = arr[index + 1];
    arr[index + 1] = temp;
  }
}

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

let divCounter = 0;

generateBtn.addEventListener('click', () => {
  divCounter = 0;
  
  arrContainer.innerHTML = '';

  const newStart = generateContainer();
  newStart.id = 'starting-array';
  arrContainer.appendChild(newStart);

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

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

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

  const startDiv = document.getElementById('starting-array');

  let arr = [...currentArray];

  let swapped = false;
  
  do {

    swapped = false;

    for (let i = 0; i < arr.length - 1; i++) {

      const stepDiv = generateContainer();
      if (divCounter === 0) {
        highlightCurrentEls(startDiv, i);
        if (!isOrdered(arr[i], arr[i + 1])) {
        swapElements(arr, i);
        swapped = true;
      }
      divCounter++;
      continue;
      }
      fillArrContainer(stepDiv, arr);
      highlightCurrentEls(stepDiv, i);
      arrContainer.appendChild(stepDiv);
      divCounter++;

      if (!isOrdered(arr[i], arr[i + 1])) {
        swapElements(arr, i);
        swapped = true;
      }

    }

  } while (swapped);

  const sortDiv = generateContainer();
  fillArrContainer(sortDiv, arr);
  arrContainer.appendChild(sortDiv);
  sortDiv.style.border = "4px solid green";

})

Your browser information:

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

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

Hey @suphxx

According to the lab file, #20 is expecting a bubbleSort() function inside addEventListner callback for sort-btn. Issue has been already reported on Github.

Meanwhile, all you have to do is change your code as follows to get it to pass.

sortBtn.addEventListener("click", bubbleSort);

function bubbleSort() {
    // your main logic
}

Thank you sir. I appreciate your help!

Happy to help! Happy coding!

I forgot to mention, while I was trying to troubleshoot the problem, I kept cycling through the program by clicking “Generate Array” and then “Sort Array” to see if anything weird happened. I noticed that every so often one of the step divs would be completely blank, but the next step would be correct and sorted correctly. That happened a couple times, and not always on the same step. One time, a bunch of the step divs were missing array elements, but the final sorted array was correct. It was weird.

While your code may have passed the tests, it’s definitely buggy.

I’m seeing this in the console for this array [71,80,14,82,34]:

Potential infinite loop detected on line 33. Tests may fail if this is not changed.
Potential infinite loop detected on line 21. Tests may fail if this is not changed.
Uncaught TypeError: Cannot read properties of undefined (reading 'appendChild')

And I’m also seeing the blank div issue you mentioned.

It’s probably related to your do/while loop. Typically, this challenge is approached with an outer loop and an inner loop.