Build a Sorting Visualizer - Build a Sorting Visualizer

Tell us what’s happening:

Stuck on Steps 18 and 20 in Build a Sorting Visualizer (Step 19 was passing)

Hi everyone,

I’ve been stuck on Steps 18 and 20 of the Build a Sorting Visualizer project for quite some time and would really appreciate some guidance.

Your code so far

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

<!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>

/* file: styles.css */

* {
    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;
  }
}

/* file: script.js */
function generateElement() {
  const min = 1;
  const max = 100;
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

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

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

const fillArrContainer = (htmlElement, arr) => {
  htmlElement.innerHTML = "";

  for (let i = 0; i < arr.length; i++) {
    const span = document.createElement("span");
    span.textContent = arr[i];
    htmlElement.append(span);
  }
};

const isOrdered = (num1, num2) => {
  return num1 <= num2;
};

const swapElements = (arr, index) => {
  if (!isOrdered(arr[index], arr[index + 1])) {
    [arr[index], arr[index + 1]] = [arr[index + 1], arr[index]];
    return true;
  }
  return false;
};

const highlightCurrentEls = (htmlElement, index) => {
  htmlElement.children[index].style.border = "2px dashed red";

  if (htmlElement.children[index + 1]) {
    htmlElement.children[index + 1].style.border = "2px dashed red";
  }
};

const generateBtn = document.getElementById("generate-btn");
const startingArr = document.getElementById("starting-array");
const arrContainer = document.getElementById("array-container");

let createdArr = [];

generateBtn.addEventListener("click", () => {
  createdArr = generateArray();

  arrContainer.querySelectorAll(":not(#starting-array)").forEach(el => el.remove());

  startingArr.innerHTML = "";
  fillArrContainer(startingArr, createdArr);
});

const sortingAlgorithm = (arr) => {
  for (let i = 0; i < arr.length - 1; i++) {
    let swapped = false;

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

      if (swapElements(arr, j)) {
        swapped = true;
      }

      const container = generateContainer();
      fillArrContainer(container, arr);
      highlightCurrentEls(container, j);
      arrContainer.append(container);
    }

    if (!swapped) {
      break;
    }
  }
};

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

function bubbleSort() {
  if (!createdArr.length) return;

  arrContainer.querySelectorAll(":not(#starting-array)")
    .forEach(el => el.remove());

  startingArr.innerHTML = "";
  fillArrContainer(startingArr, createdArr);
  highlightCurrentEls(startingArr, 0);

  const arrCopy = [...createdArr];

  sortingAlgorithm(arrCopy);

  const genContainer = generateContainer();
  fillArrContainer(genContainer, arrCopy);
  highlightCurrentEls(genContainer, 0);
  arrContainer.append(genContainer);
}

sortBtn.addEventListener("click", bubbleSort);


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/150.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

Welcome to the forum @loki310806,

Please check your loop variables. The outer loop should loop over the length of the array if necessary, and the inner loop should loop over each pair of numbers in the array for each iteration of the outer loop.

Your starting array should be included in the bubble sort; it just needs to be treated differently since it already has values.

The pair of numbers highlighted in a div shouldn’t show up as swapped until the next div.

Try checking your code against the example app. You can even temporarily hard code the same array to replace your call to generateArray() in the generate button’s listener.

And please don’t overlook this instruction:

The algorithm stops after one cycle completes with no swaps.

Update:

Here’s a comparison of your code’s output and the example app’s output for the same array:

Example app:

Your code:

Happy coding

Oh! Thank you. I reviewed it and changed the code, now it’s working. Thank you for the help
Corrected the loop logic so the outer loop controls the bubble sort passes and the inner loop compares adjacent pairs during each pass also included the initial unsorted array as the first step in visualization, now it works, i completed the lab thank you again for the help and guidance