Build a Sorting Visualizer - Build a Sorting Visualizer

Tell us what’s happening:

Have been stuck for hours on 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.
I have checked the DOM and it all looks good. The sorting algorithm matches the demo. Start and end sorts are included. When I try to disable further sorting to avoid extra divs, #20 fails also. Problem is similar to other unresolved posts online.

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

#sorted-array {
    border: 4px solid green !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 */
/* Bubble Sort
The Bubble Sort algorithm sorts a sequence of integers by comparing couples of adjacent elements starting from the beginning of the sequence. If the first element is greater than the second one, it swaps them. Then, it proceeds with the following couple. When the last element of the sequence is reached, it starts a new cycle from the beginning of the sequence, and repeats the process until the elements are sorted. The algorithm stops after one cycle completes with no swaps. */

/* generateElement() returns a random integer between 1 and 100, inclusive. */
const generateElement = () => {
  return Math.floor(Math.random() * 100) + 1;
}

/* generateArray() uses the generateElement function to return an array containing five random integers. */
const generateArray = () => {
  const randArr = [];
  let randVal;
  for (let i=0; i<5; i++) {
    randVal = generateElement();
    randArr.push(randVal);
  }
  return randArr;
}

/* generateContainer() creates and returns an empty div element. */
const generateContainer = () => {
  /* Usage: const mydiv = generateContainer()
            document.body.appendChild(mydiv)
            This appends to the <body>
  */
  const newDiv = document.createElement("div")
  return newDiv;
}

/* fillArrContainer() takes an HTML element as the first argument and an array as the second argument. It fills the element passed as the first argument to the function with five span elements with the text of an integer from the array passed as the second argument to the function. */
const fillArrContainer = (eltHTML, arr) => {
  eltHTML.innerHTML = "";
  for (let i=0; i<arr.length; i++) {
    eltHTML.innerHTML += `<span>${arr[i].toString()}</span>`;
  }  
}
 
/* isOrdered() takes two integers and returns a boolean indicating if the first integer is less than or equal to the second. */
function isOrdered (int1, int2) {
  return int1 <= int2;
}

/* swapElements() takes an array of integers and a numeric index. It modifies the array in place by swapping the element at the passed index and the following element if isOrdered() returns false. */
const swapElements = (intArr, index) => {
  if (index < 0 || index >= intArr.length - 1) {
    console.error("Invalid index provided.")
    return;
  }
  if (isOrdered(intArr[index], intArr[index + 1])) {
    return
  } else {
    let temp = intArr[index];
    intArr[index] = intArr[index + 1];
    intArr[index + 1] = temp;
  }
}

/* highlightCurrentEls() takes an HTML element and a numeric index. It sets the border of the given element's child at the given index, and the child immediately after the index, to have a dashed style, a red color, and a width of your choice. */
const highlightCurrentEls = (eltHTML, index) => {
  const childElements = eltHTML.children;
  childElements[index].style.border = '2px dashed red';
  childElements[index + 1].style.border = '2px dashed red';
} 

/* Main process ---------------------*/
/* When you click #generate-btn you should use the fillArrContainer function to fill #starting-array with five span elements, each with a random number as its text. If present, other elements should be removed from #array-container. */
const generateBtn = document.getElementById("generate-btn");
const startingArr = document.getElementById("starting-array");
const arrayContainer = document.getElementById("array-container");
let sortArr;
generateBtn.addEventListener("click", () => {
  const toRemove = arrayContainer.querySelectorAll(
    ':not([id="starting-array"])');
  toRemove.forEach(element => {element.remove();}); 
  console.log(startingArr.innerHTML);
  sortArr = generateArray();
  fillArrContainer(startingArr, sortArr);
});

/* Implement the Bubble Sort algorithm so that after you click #sort-btn, #array-container contains a div element for each of 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. */
const sortBtn = document.getElementById("sort-btn");
sortBtn.addEventListener("click", () => {
  /* while (arrayContainer.children.length > 1) {
    return;
  } */

  // Create HTML for initial generated array and highlight 1st 2 elts (should already be there)
  // loop until there is a cycle with no swaps
  let swaps;
  let firstIteration = true;
  
  do {
    swaps = false;
    for (let i=0; i<sortArr.length - 1; i++) {
     
      // compare pairs
      if (isOrdered(sortArr[i],sortArr[i+1])) {
        swaps ||= false;
      } else {
        swaps ||= true;
        swapElements(sortArr,i);
        console.log(sortArr);
      }
      // Create and output div
      if (firstIteration) {
        highlightCurrentEls(startingArr,i);
        firstIteration = false;
      } else {
        const myDiv = generateContainer();
        fillArrContainer(myDiv, sortArr);
        highlightCurrentEls(myDiv,i);
        arrayContainer.appendChild(myDiv);
      }
    }
    // update HTML if swaps is true, else exit

  } while (swaps);
  // Display final sorted array (id="sorted-array")
  const myDiv = generateContainer();
  myDiv.id = "sorted-array";
  fillArrContainer(myDiv, sortArr);
  arrayContainer.appendChild(myDiv);
})

Your browser information:

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

Challenge Information:

Build a Sorting Visualizer - Build a Sorting Visualizer

We’ll need to see your code, please:

When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

1 Like