Build a Sorting Visualizer - Build a Sorting Visualizer

Tell us what’s happening:

I am not passing the 18th test, I have already hard coded an array from the example generator and see that it isn’t going all the way through to the end of the array, but I don’t know what to change to fix it. I just need to pointed in the right direction. Thanks :slight_smile:

Your code so far

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

/* file: styles.css */

/* file: script.js */
```
const generateBtn = document.getElementById("generate-btn");
const sortBtn = document.getElementById("sort-btn");

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

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

const generateArray = () => Array.from({length: 5}, () => generateElement());

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


const fillArrContainer = (el, arr) => {
  el.innerHTML = '';
 return arr.forEach(item => el.innerHTML += `<span>${item}</span>`)
};

const isOrdered = (a, b) => a <= b;
  
const swapElements = (arr, i) => {
let temp;
 if(!isOrdered(arr[i], arr[i + 1])){
    temp =  arr[i];
    arr[i] = arr[i + 1];
    arr[i + 1] = temp;
   
  };


};

const highlightCurrentEls = (el, i) => {
 el.children[i].style.border = "3px, dashed, red";
 el.children[i + 1].style.border = "3px, dashed, red";
};

 

 
let array = []
generateBtn.addEventListener("click", () => {
  arrContainer.replaceChildren(startingArr);
  // startingArr.innerHTML = '';
  array =  generateArray(); // [21, 71, 8, 57, 84]
  fillArrContainer(startingArr, array);
  
  });



sortBtn.addEventListener("click", () => { 
   highlightCurrentEls(startingArr, 0);
  
for(let i = 0; i < array.length - 1; i++){
  for(let j = 0; j < array.length - i - 1; j++){
      swapElements(array, j);
      let container = generateContainer();
      fillArrContainer(container, array);
      highlightCurrentEls(container, j);
      arrContainer.append(container);
       
     };
  };
      let container = generateContainer();
      fillArrContainer(container, array);
      arrContainer.append(container);
      container.style.border = "3px solid green";
      sortBtn.disabled;
});
```

Your browser information:

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

Challenge Information:

Build a Sorting Visualizer - Build a Sorting Visualizer

Is your iterator set to loop over each pair in the array?

Well thats what I thought the nested loops in the sortBtn event listener function were doing, but obviously its not working, I’ve tried a bunch of different things but I’m not sure if I have to change something in those loops or the logic or if I need to change my swapElements function or both

What debugging have you done? Have you logged j?

I logged j and it wasn’t cycling all the way through . So now I have I rewrote some of the logic in the nested loops and it is cycling through the array all the way now, but it’s also giving like ten extra divs after sorting the array all the way through; and now I am not passing 18 and 19

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

I’m not seeing that issue when I just make your loop counter changes. Maybe you should roll back to the code you first posted and make only those changes. Then look at the example app again. See how the second level has the second pair highlighted rather than the first? You need to handle that.

Ok I tried what you said but it gave the same result… I just took a screen shot to show you what I am talking about. About the 14th row down is when it should stop producing the div elements because all of the numbers are already in order but it keeps going.

I’ve also have had trouble getting the starting arr to highlight thats why I have this code right before the nested loops ```highlightCurrentEls(startingArr, 0);``` that highlights the startingArr but because it is out of the for loops it is detached from the iteration. I will keep working to figure out how to fix that though.

Maybe try this again. Your first and second levels are highlighting the same pair, meaning you are returning one more level than you need. The code is stopping where it needs to (look at the example - it should stop after an iteration with no swaps), but you are starting your swaps one level too late.

So this ^ pic is from the example

this one is my code. Its giving way too many containers and also it is starting a container too late. But I don’t know how to change it, everything I do hasn’t helped.

Please post your updated code. What have you done to debug so far?

```

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

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

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

const generateArray = () => Array.from({length: 5}, () => generateElement());

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


const fillArrContainer = (el, arr) => {
  el.innerHTML = '';
 return arr.forEach(item => el.innerHTML += `<span>${item}</span>`);
};

const isOrdered = (a, b) => a <= b;
  
const swapElements = (arr, i) => {
 if(!isOrdered(arr[i], arr[i + 1])){
    [arr[i + 1], arr[i]] = [arr[i], arr[i + 1]]
   };
  
};

const highlightCurrentEls = (el, i) => {
 el.children[i].style.border = "3px, dashed, red";
 el.children[i + 1].style.border = "3px, dashed, red";
};

 

 
let array = generateArray();


generateBtn.addEventListener("click", () => {
  arrContainer.replaceChildren(startingArr);
   // array =  [21, 71, 8, 57, 84]
  fillArrContainer(startingArr, array);
  
  });



sortBtn.addEventListener("click", () => { 
  highlightCurrentEls(startingArr, 0);
  
for(let i = 0; i < array.length; i++){
  
  for(let j = 0; j < array.length - 1; j++){
    console.log(j, i);
    
      let container = generateContainer();
       arrContainer.append(container);
      swapElements(array, j);
      fillArrContainer(container, array);
      highlightCurrentEls(container, j);
     
 }; 
   };
      let container = generateContainer();
      fillArrContainer(container, array);
      arrContainer.append(container);
      container.style.border = "3px solid green";
      sortBtn.disabled;
}); 

```

As far as debugging, I have done enough to understand that the everytime I click the sort button, it will run through each number in the array 5 times (the same length of the array). So I get the same amount of divs each time so I will get 5 sets of it running through the loop. I have messed around A LOT with the loops but nothing has changed it this remains seemingly the best code I’ve come up with, I also understand that the startingArr is not part of that loop and I have tried also a lot of things to try and get it to be part of the looping process but with no success.

You are on the right track by realizing that the startingArr should be part of the loop. Think about what will be true if it’s the startingArr and what does not need to happen with the startingArr compared to what does need to happen for all other iterations. And think about the order in which things should happen in the loop. You also need a way to determine when the sort is done. I don’t see anything tracking that in your code.

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

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


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

const generateArray = () => Array.from({length: 5}, () => generateElement())


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

let array = generateArray();
//let array = [83,57,43,25,52]  
  

const fillArrContainer = (el, arr) => {
  el.innerHTML = '';
 return arr.forEach(item => el.innerHTML += `<span>${item}</span>`)
};


const isOrdered = (a, b) => a <= b;

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


const highlightCurrentEls = (el, i) => {
    el.children[i].style.border = "3px, dashed, red";
    el.children[i + 1].style.border = "3px, dashed, red";
  }


generateBtn.addEventListener("click", () => {
  arrContainer.replaceChildren(startingArr);
 fillArrContainer(startingArr, array);
});

const isSorted = (arr) => {
  for(let i = 0; i < arr.length; i++){
    if(arr[i] > arr[i + 1]){
      return false;
    };
    };
  return true;
};


sortBtn.addEventListener("click", () => {
 
  fillArrContainer(startingArr, array);
  let count = 0;
  highlightCurrentEls(startingArr, count);
  
  
for(let i = 0; i < array.length; i++){
 for(let j = 0; j < array.length - 1; j++){
   count++;

     console.log(i, j);
    if(count === 1){
     swapElements(array, j);
     }else {  
      let container = generateContainer();
      arrContainer.append(container);
      fillArrContainer(container, array);
      highlightCurrentEls(container, j);
      swapElements(array, j);
      console.log("Sorted:", isSorted(array));
    };
 };
     const sorted = isSorted(array);
    
  if(sorted){ 
      i = array.length;
  for(let l = 0; l < array.length - 1; l++){
    let container = generateContainer();
      arrContainer.append(container); 
      fillArrContainer(container, array);
      highlightCurrentEls(container, l);
    
  };
         
      };
  }; 
 
  let finalContainer = generateContainer();
  arrContainer.appendChild(finalContainer);
  fillArrContainer(finalContainer, array);
  finalContainer.style.border = "3px, green, solid";
  
});

So I’ve updated my code to where it looks like it is doing everything it is supposed to even when I have tested it with an array from the example code, and I am still not passing the 18th and 19th test. Just wondering if you could point me in the right direction again possibly because I’m not sure why it is failing now, or maybe help me understand what I could do to debug?

Test around the example project again.

What happens if you click the “Generate” multiple times? How does that compare to what your code does?

Pay attention to when the “Sort” button is displayed. What happens in your code if “Sort” is clicked before “Generate” or after the sort completes?

That was the issue. I passed finally! Thank you so much for your help!! :grin: