Build a Sorting Visualizer - Build a Sorting Visualizer

Tell us what’s happening:

I can’t figure out why requirement 18 isn’t working, I have tried everything.
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.

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 */
const generateElement = ()=>{
  return Math.floor(Math.random() * 100) + 1
}
const generateArray = ()=>{
  return [generateElement(),generateElement(),generateElement(),generateElement(),generateElement()]
}
const generateContainer = ()=> document.createElement('div');
const fillArrContainer = (el, arr) => {
  el.innerHTML = '';
  arr.forEach(n => {
    const span = document.createElement('span');
    span.innerText = n;
    el.append(span);
  });
}
const isOrdered = (a,b)=> a <= b ? true : false;
const swapElements = (arr,i)=>{
  if(!arr[i+1]) return;
    else if(!isOrdered(arr[i],arr[i+1])){
      [arr[i],arr[i+1]] = [arr[i+1],arr[i]]
    }
}
const highlightCurrentEls = (el,i)=>{
  if(!el.children[i+1]) return;
  el.children[i].style.border = '2px dashed red';
  el.children[i+1].style.border = '2px dashed red';
}

const generateBtn = document.getElementById('generate-btn');
let startingArr = document.getElementById('starting-array');
const sortBtn = document.getElementById('sort-btn');
const container = document.getElementById('array-container');


generateBtn.onclick = ()=>{
  if(container.children.length > 1) {
    container.innerHTML = '';
    const startDiv = generateContainer();
    startDiv.id = 'starting-array';
    container.append(startDiv);
    startingArr = startDiv;
  }
  startingArr.innerHTML = '';
  fillArrContainer(startingArr, generateArray());
};

sortBtn.onclick = ()=>{
  // Clear previous sort steps
  while(container.children.length > 1) {
    container.lastChild.remove();
  }
  startingArr.remove()
  
  const firstArr = Array.from(startingArr.children);
  let newArr = [];
  firstArr.forEach(el => newArr.push(Number(el.innerText)));
  for(let i = 0; i < newArr.length - 1; i++){
    for(let j = 0; j < newArr.length - i - 1; j++){
      let div = generateContainer();
      div.classList.add('div');
      fillArrContainer(div,newArr);
      highlightCurrentEls(div,j);
      swapElements(newArr,j);
      container.append(div);
    }
  }
  container.querySelectorAll('.div')[0].id = 'starting-array';
  Array.from(container.lastChild.children).forEach(el => el.style = '')
  container.lastChild.style.borderColor = 'green'
}

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

Open the example project. Does the starting screen look like yours?

Click “Generate Array” then “Sort Array”. Take a screenshot.

Now in generateBtn.onclick (this is dated; use addEventListener instead), replace your call to generateArray() with the hard-coded array that was generated in the example project.

Then compare the screenshot from the example project to what your code produces.

i see the difference but i still can’t figure out the solution

What is the difference? If you can describe it I think it will help

Search the forum as well. Everyone seems to get this wrong in the exact same way.

https://forum.freecodecamp.org/search?q=Build%20a%20Sorting%20Visualizer%20order%3Alatest

I can see that in the example code (left side), the algorithm stops when a full pass has been done with no swaps indicating that it’s sorted but in the right side(my version) it checks for less pairs with every pass

Ok, what’s preventing you from changing it?

I’m trying to think of how to indicate if a swap happened

Yes, sounds like a good idea

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.