# Build a Sorting Visualizer - Build a Sorting Visualizer

**URL:** <https://forum.freecodecamp.org/t/build-a-sorting-visualizer-build-a-sorting-visualizer/802138>\
**Category:** Curriculum Help\
**Tags:** javascript\
**Created:** [October 12, 2026, 2:25pm UTC](https://forum.freecodecamp.org/t/build-a-sorting-visualizer-build-a-sorting-visualizer/802138 "2026-10-12T14:25:15Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![inokchristine24](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/inokchristine24/32/422602_2.png) [@inokchristine24](https://forum.freecodecamp.org/u/inokchristine24)\
**Post date:** [October 12, 2026, 2:25pm UTC](https://forum.freecodecamp.org/t/build-a-sorting-visualizer-build-a-sorting-visualizer/802138/1 "2026-10-12T14:25:15Z")

</div>

### Tell us what’s happening:

I have tried the project severally but it still fails the tests

### Your code so far

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

```

```css
/* file: styles.css */

```

```js
/* 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/155.0.0.0 Safari/537.36`

### Challenge Information:

Build a Sorting Visualizer - Build a Sorting Visualizer

> **[freeCodeCamp.org](https://www.freecodecamp.org/learn/javascript-v9/lab-sorting-visualizer/build-a-sorting-visualizer)**
>
> Learn to Code for Free

GitHub Link: [freeCodeCamp/curriculum/challenges/english/blocks/lab-sorting-visualizer/6716249b5405164036fd0b0d.md at main · freeCodeCamp/freeCodeCamp · GitHub](https://github.com/freeCodeCamp/freeCodeCamp/blob/main/curriculum/challenges/english/blocks/lab-sorting-visualizer/6716249b5405164036fd0b0d.md)

---

<div class="post-metadata">

**Author:** ![dhess](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/dhess/32/406235_2.png) [@dhess](https://forum.freecodecamp.org/u/dhess)\
**Post date:** [October 12, 2026, 2:25pm UTC](https://forum.freecodecamp.org/t/build-a-sorting-visualizer-build-a-sorting-visualizer/802138/2 "2026-10-12T14:25:57Z")

</div>

Welcome to the forum @inokchristine24,

Your code was too long to be automatically inserted by the help button.

Please update the message, or reply to this one, to include your code, formatted as follows:

There are two ways you can format your code to make it easier to read and test:

1. After you copy/paste your code into the editor, select it by dragging your cursor over it then click the (`</>`) button in the toolbar to automatically wrap your code in backticks. (You can click on the animated demo image below to enlarge it.)

 ![](https://global.discourse-cdn.com/freecodecamp/original/3X/1/b/1b18854f1059217f29370444396145cc3a0cd8ae.gif)

1. Manually add three backticks on a new line above your code and on a new line after your code. Note that a backtick is NOT the same as a single quote('). To find the backtick key on your keyboard, see [this post](https://forum.freecodecamp.org/t/forum-code-formatting/25574).

To see changes to your post as you make them, you can click the (`M+`) button on the toolbar to bring up the rich text editor:

 ![image](https://global.discourse-cdn.com/freecodecamp/original/4X/a/a/1/aa16828d97d1fd4a1aa0f864a850415f01dc9d2b.png)

Happy coding

---

<div class="post-metadata">

**Author:** ![inokchristine24](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/inokchristine24/32/422602_2.png) [@inokchristine24](https://forum.freecodecamp.org/u/inokchristine24)\
**Post date:** [October 12, 2026, 2:30pm UTC](https://forum.freecodecamp.org/t/build-a-sorting-visualizer-build-a-sorting-visualizer/802138/4 "2026-10-12T14:30:11Z")

</div>

````auto
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);
});
```

````

---

<div class="post-metadata">

**Author:** ![dhess](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/dhess/32/406235_2.png) [@dhess](https://forum.freecodecamp.org/u/dhess)\
**Post date:** [October 12, 2026, 2:49pm UTC](https://forum.freecodecamp.org/t/build-a-sorting-visualizer-build-a-sorting-visualizer/802138/5 "2026-10-12T14:49:29Z")

</div>

Hi @inokchristine24,

> [@inokchristine24](#):
>
> `for (let i = 0; i < n - 1; i++)`

Is your outer loop running maximum iterations that total the length of the array?

> [@inokchristine24](#):
>
> `for (let j = 0; j < n - i - 1; j++) {`

Is your inner loop looking at each pair of numbers in the array for every iteration of the outer loop?

Try comparing how your code behaves to the example app. You can even temporarily hard code an array from the example app after taking a screenshot so you can easily compare.

Here’s one that I did —

From the example app:

 ![image](https://global.discourse-cdn.com/freecodecamp/original/4X/e/e/d/eed33a493f1a56ef54eafda371af1f886612bc6a.png)

From your code:

 ![image](https://global.discourse-cdn.com/freecodecamp/original/4X/c/3/c/c3cf0a2f358f3b5817bf26e94be20f8101f78569.png)

Happy coding

---

<div class="post-metadata">

**Author:** ![inokchristine24](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/inokchristine24/32/422602_2.png) [@inokchristine24](https://forum.freecodecamp.org/u/inokchristine24)\
**Post date:** [October 12, 2026, 3:14pm UTC](https://forum.freecodecamp.org/t/build-a-sorting-visualizer-build-a-sorting-visualizer/802138/6 "2026-10-12T15:14:14Z")

</div>

````auto
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 = [66,41,54,91,78];
  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");

  arrayContainer.innerHTML = "";

  let arr = currentArray.slice();
  const n = arr.length;

  // Show the starting array and highlight the first pair
  fillArrContainer(startingArrayDiv, arr);
  highlightCurrentEls(startingArrayDiv, 0);

  let swapped;

  do {
    swapped = false;

    for (let j = 0; j < n - 1; j++) {
      // Compare the current adjacent pair
      if (!isOrdered(arr[j], arr[j + 1])) {
        swapElements(arr, j);
        swapped = true;
      }

      // Record the array state after this comparison
      const stepContainer = generateContainer();
      fillArrContainer(stepContainer, arr);
      highlightCurrentEls(stepContainer, j);
      arrayContainer.appendChild(stepContainer);
    }
  } while (swapped);

  // Append the final sorted array without highlights
  const finalContainer = generateContainer();
  fillArrContainer(finalContainer, arr);

  // Mark the final row as sorted if your CSS supports it
  finalContainer.classList.add("sorted");

  arrayContainer.appendChild(finalContainer);
});
```

````

---

<div class="post-metadata">

**Author:** ![ILM](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/ilm/32/363239_2.png) [@ILM](https://forum.freecodecamp.org/u/ILM)\
**Post date:** [October 12, 2026, 6:03pm UTC](https://forum.freecodecamp.org/t/build-a-sorting-visualizer-build-a-sorting-visualizer/802138/7 "2026-10-12T18:03:18Z")

</div>

instead of just posting code, can you tell us something? like what you need help debugging, what you tried since last time, please

---

<div class="post-metadata">

**Author:** ![inokchristine24](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/inokchristine24/32/422602_2.png) [@inokchristine24](https://forum.freecodecamp.org/u/inokchristine24)\
**Post date:** [October 13, 2026, 10:43am UTC](https://forum.freecodecamp.org/t/build-a-sorting-visualizer-build-a-sorting-visualizer/802138/8 "2026-10-13T10:43:08Z")

</div>

my code still fails these tests:

```auto
17. When #starting-array already contains a generated array, or #array-container contains the sorted array, clicking the #generate-btn should remove other elements in the #array-container, leaving only #starting-array with newly generated numbers.
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.
19. After you click #sort-btn, each div within #array-container should contain five span, each with a number as its text, and arranged to represent the steps required by Bubble Sort algorithm to sort the starting array.
20. When you click the #sort-btn, you should make use of the highlightCurrentEls function to highlight the elements being compared in each step.
21. After you click #sort-btn, #starting-array should represent the starting step with the initial array and the first two integers highlighted using highlightCurrentEls.

```

---

<div class="post-metadata">

**Author:** ![inokchristine24](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/inokchristine24/32/422602_2.png) [@inokchristine24](https://forum.freecodecamp.org/u/inokchristine24)\
**Post date:** [October 13, 2026, 10:47am UTC](https://forum.freecodecamp.org/t/build-a-sorting-visualizer-build-a-sorting-visualizer/802138/9 "2026-10-13T10:47:39Z")

</div>

i have finally solved the problem thank you
