Build a Sorting Visualizer - Build a Sorting Visualizer

Tell us what’s happening:

Hi,
my code give me a result that looks like the one of the exemple, but i still am stucked with this error :
“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.”…

I dont understand, as i have all the divs requested, have my starting array and my sorted array that looks corrects.

thanks for the help. :slight_smile:

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

#ending-array {
    border: 4px solid darkgreen !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 generateBtn = document.getElementById("generate-btn");
const startingArray = document.getElementById("starting-array");
const arrayContainer = document.getElementById("array-container");
const sortBtn = document.getElementById("sort-btn");

// function to generate a number from 1 to 100
function generateElement() {
  return Math.ceil(Math.random() * 100);
};

// function to generate an Array of 5 numbers
function generateArray() {
  const randomArray = [];
  do {
    const newNumber = generateElement();
    if (!randomArray.includes(newNumber)){
    randomArray.push(newNumber);
    } 
  } while (randomArray.length < 5);
  return randomArray;
};
//console.log(generateArray())

// function to create a DIV
function generateContainer() {
  return document.createElement("div");
};

// function to fill element with 5 spans
function fillArrContainer(html, array) {
  let spanToAdd = "";
  for (let i = 0; i < 5; i++) {
    spanToAdd += `<span>${array[i]}</span>`
  } 
  return html.innerHTML = spanToAdd;
}
//console.log(fillArrContainer(containerCreator, generateArray()))

// function to check 2 integers order
function isOrdered(int1, int2) {
  return int1 <= int2;
};
// function that swaps 2 integers 
function swapElements(array, index) {
  let nextIndex = index + 1;
  if (!isOrdered(array[index], array[nextIndex])) {
    [array[index], array[nextIndex]] = [array[nextIndex], array[index]];
  } else {
    [array[index], array[nextIndex]] = [array[index], array[nextIndex]];
  }
  return array;
};
//console.log(swapElements(generateArray(), 0))

// function that highlight checked elements
function highlightCurrentEls(parentEl, index) {
  const child1 = parentEl.children[index];
  const child2 = parentEl.children[index + 1];

  if (child1) {
    child1.style.border = "2px dashed red";
  }
  if (child2) {
    child2.style.border = "2px dashed red";
  }
};

let generatedArray = [];

// generate array button click
generateBtn.addEventListener("click", () => {
  Array.from(arrayContainer.children).forEach(child => {
    if (child !== startingArray) {
      arrayContainer.removeChild(child);
    }
  });
  startingArray.innerHTML = "";
  generatedArray = generateArray();
  fillArrContainer(startingArray, generatedArray);
  return generatedArray;
});

// sort array button click
sortBtn.addEventListener("click", () => {

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

  let index = 0;
  highlightCurrentEls(startingArray, index);
  swapElements(generatedArray, index);
  index +=1;
  
  do {
    console.log(index)
    console.log(generatedArray);
    
    const containerCreator = generateContainer();
    arrayContainer.append(containerCreator);
    fillArrContainer(containerCreator, generatedArray);
    highlightCurrentEls(containerCreator, index);
    swapElements(generatedArray, index);
    index += 1;
      if (index >= generatedArray.length - 1) {
        index = 0;
      }
  } while (!isSorted(generatedArray));
  do {
    console.log(index)
    console.log(generatedArray);
    
    const containerCreator = generateContainer();
    arrayContainer.append(containerCreator);
    fillArrContainer(containerCreator, generatedArray);
    highlightCurrentEls(containerCreator, index);
    swapElements(generatedArray, index);
    index += 1;
     if (index >= generatedArray.length - 1) {
        break;
      }
  } while (index <= generatedArray.length - 1);

  const endingArray = generateContainer();
  endingArray.id = "ending-array";
  endingArray.style.border = "4px solid darkgreen";
  fillArrContainer(endingArray, generatedArray);
  arrayContainer.append(endingArray);
});

![49D00B76-6459-4499-8572-1F01CD726F81_4_5005_c|274x406](upload://8ylSmihDk3nurkoeT9PIlZFxbBI.jpeg)


Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36

Challenge Information:

Build a Sorting Visualizer - Build a Sorting Visualizer
https://www.freecodecamp.org/learn/full-stack-developer/lab-sorting-visualizer/build-a-sorting-visualizer

I tested your code and it seems to not be working correctly.
In the example above, you need to repeat the sort until no swaps are made.
(so you would need to show another 4 divs)

hi,
thanks for the answer but i dont get it.
the 2 last lines are the same, so, which swap is missing ?
(im French, so perhaps i dont totally get the task they want precisely because of my English :/)

ohh i think i get it, before putting the array sorted in green, i need to do one last full iteration without swap ? that s it ?

1 Like

I passed ! Many thanks for the clue :slight_smile:
(but i feel my code is horribly complicated)

removed by mod
  
  
  


Please don’t add solution code here

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge. How to Help Someone with Their Code Using the Socratic Method

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

1 Like

oups, really sorry !!! my bad… :anguished_face:

1 Like

Not a problem at all.

Now you know, and knowing is half the battle :+1:

1 Like

many thanks for the time you guys give to help us in our learning :folded_hands:

1 Like

if you need someone to review your solution and provide feedback, you can do that but move the topic to the “Code Feedback” section

thanks for the information. i will give an eye !
have a nice day

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