Build a Sorting Visualizer - Build a Sorting Visualizer

Tell us what’s happening:

Hello Coders,

I am failing test #19

I have tried matching the outputs, and they look similar. Please take a look and let me know if you see any issues. Thanks!

// running tests
19. After you click #sort-btn, each div within #array-container should contain five spans, each with a number as its text, and arranged to represent the steps required bythe Bubble Sort algorithm to sort the starting array.
// tests completed

Your code so far

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

/* file: styles.css */

/* file: script.js */
const arrayContainer = document.querySelector("#array-container")
const startingArray = document.querySelector("#starting-array")

let generateElement = () => Math.floor(Math.random() * 100 + 1)

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

let generateContainer = () => {
  return document.createElement('div')
}

let fillArrContainer = (el, arr) => {
  el.innerHTML = arr.map(n => `<span>${n}</span>`).join("")
}

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

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

function highlightCurrentEls(el, index) {
  el.children[index].style.border = "2px dashed red"
  el.children[index + 1].style.border = "2px dashed red"
}

document.querySelector("#generate-btn").addEventListener("click", () => {
  // remove all children
  arrayContainer.innerHTML = ""
  arrayContainer.append(startingArray)
  fillArrContainer(startingArray, generateArray())
})

document.querySelector("#sort-btn").addEventListener("click", () => {
  arrayContainer.innerHTML = ""
  arrayContainer.append(startingArray)
  highlightCurrentEls(startingArray, 0)
  let arr = [...startingArray.children].map(s => Number(s.textContent))
  // let arr = [73,19,79,26,97]

  let firstpass = true
  let swapped = true
  while (swapped) {
    swapped = false
    for (let i = 0; i < arr.length - 1; i++) {
      if (firstpass == true) {
        firstpass = false
        continue
      }
      const swapStep = document.createElement("div")
      fillArrContainer(swapStep, arr)
      highlightCurrentEls(swapStep, i)
      arrayContainer.append(swapStep)
      // swap for next step
      if (!isOrdered(arr[i], arr[i + 1])) {
        swapElements(arr, i)
        swapped = true
      }
    }

  }
  // final sorted step
  const finalStep = document.createElement("div")
  fillArrContainer(finalStep, arr)
  arrayContainer.append(finalStep)
})



Your browser information:

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

Challenge Information:

Build a Sorting Visualizer - Build a Sorting Visualizer

Figured it out, I wasn’t swapping in the if(firstpass == true) block.

1 Like