Build a Sorting Visualizer - Build a Sorting Visualizer

Tell us what’s happening:

even though the visualizer working perfectly

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.

not meeting need Elpppppppp

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

let currentArray = [];

function generateElement() {
  return Math.floor(Math.random() * 100 +1);
}

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

function generateContainer() {
  return document.createElement("div");
}

function fillArrContainer(container, arr) {
  container.innerHTML = "";
  arr.forEach(num => {
    const span = document.createElement("span");
    span.textContent = num;
    container.appendChild(span);
  });
}

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

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

function highlightCurrentEls(container, index) {
  const children = container.children;

  if (index < children.length) {
    children[index].style.border = "2px dashed red";
  }

  if (index + 1 < children.length) {
    children[index + 1].style.border = "2px dashed red";
  }
}

document.getElementById("generate-btn").addEventListener("click", function () {
  const arrayContainer = document.getElementById("array-container");
  arrayContainer.innerHTML = "";

  const startingArrayDiv = document.createElement("div");
  startingArrayDiv.id = "starting-array";
  arrayContainer.appendChild(startingArrayDiv);

  currentArray = generateArray();
  fillArrContainer(startingArrayDiv, currentArray);
});

document.getElementById("sort-btn").addEventListener("click", function () {
  if (currentArray.length === 0) return;

  const arrayContainer = document.getElementById("array-container");
  const startingArrayDiv = document.getElementById("starting-array");

  fillArrContainer(startingArrayDiv, currentArray);
  highlightCurrentEls(startingArrayDiv, 0);

  let arr = [...currentArray];
  const n = arr.length;
  let swapped;

  for (let i = 0; i < n - 1; i++) {
    swapped = false;

    for (let j = 0; j < n - i - 1; j++) {
      if (i === 0 && j === 0) {
        if (swapElements(arr, j)) swapped = true;
        continue;
      }

      const stepContainer = generateContainer();
      fillArrContainer(stepContainer, arr);
      highlightCurrentEls(stepContainer, j);
      arrayContainer.appendChild(stepContainer);

      if (swapElements(arr, j)) swapped = true;
    }

    if (!swapped) break;
  }

  const finalContainer = generateContainer();
  fillArrContainer(finalContainer, arr);
  arrayContainer.appendChild(finalContainer);
});


Your browser information:

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

Challenge Information:

Build a Sorting Visualizer - Build a Sorting Visualizer

Did you compare what the example app does to what your app does? Your app is not working as expected.

This is what the example app generates:


And this is what your app generates:

sorry I copy pasted the guys code I was comparing with but can’t edit it anymore should I create a new post?

Why do you need to compare code to someone else?

Observe how the example app works. Read the instructions and follow them.

let currentArray = [];

function generateElement() {
  return Math.floor(Math.random() * 100) + 1;
}

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

function generateContainer() {
  return document.createElement("div");
}

function fillArrContainer(container, arr) {
  container.innerHTML = "";

  arr.forEach(num => {
    const span = document.createElement("span");
    span.textContent = num;
    container.appendChild(span);
  });
}

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

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

function highlightCurrentEls(container, index) {
  const children = container.children;

  if (index < children.length) {
    children[index].style.border = "2px dashed red";
  }

  if (index + 1 < children.length) {
    children[index + 1].style.border = "2px dashed red";
  }
}

document.getElementById("generate-btn").addEventListener("click",()=> {
  const arrayContainer = document.getElementById("array-container");
  arrayContainer.innerHTML = "";

  const startingArrayDiv = document.createElement("div");
  startingArrayDiv.id = "starting-array";
  arrayContainer.appendChild(startingArrayDiv);

  currentArray = generateArray();
  fillArrContainer(startingArrayDiv, currentArray);
  
  document.getElementById("sort-btn").style.display = "inline-block";
});

document.getElementById("sort-btn").addEventListener("click",()=> {
  if (currentArray.length === 0) return;

  const arrayContainer = document.getElementById("array-container");
  const startingArrayDiv = document.getElementById("starting-array");

  fillArrContainer(startingArrayDiv, currentArray);
  highlightCurrentEls(startingArrayDiv, 0);

  let arr = [...currentArray];
  const n = arr.length;
  let isFirstStep = true;
  let swapped;

  for (let i = 0; i < n - 1; i++) {
    swapped = false;
    
    for (let j = 0; j < n - i - 1; j++) {
      if (isFirstStep) {
        isFirstStep = false;
        swapElements(arr, j);
        if (!isOrdered(arr[j], arr[j + 1])) {
          swapped = true;
        }
        continue;
      }

      const stepContainer = generateContainer();
      fillArrContainer(stepContainer, arr);
      highlightCurrentEls(stepContainer, j);
      arrayContainer.appendChild(stepContainer);

      const beforeSwap = arr[j];
      swapElements(arr, j);
      
      if (arr[j] !== beforeSwap) {
        swapped = true;
      }
    }
    
    if (!swapped) {
      break;
    }
  }
  const finalContainer = generateContainer();
  fillArrContainer(finalContainer, arr);
  finalContainer.style.border = "3px solid green";
  arrayContainer.appendChild(finalContainer);

  document.getElementById("sort-btn").style.display = "none";
});

This is your actual code and the code you posted before was written by someone else?

was checking for if I’m missing some step or typo

ok got it btw I posted my code just above can discuses now?

This is the problem:

yea it was someone from the help form he was also missing the 18th condition

If they have the same problem how is their code going to help?

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.

This is how the algo should work. Look at the screenshots provided and follow the algorithm described here.

no no that was from that guy mine is actually like this

I tested yours. It’s the same problem. Look at the example app or the screenshots above again. Or read the text of the algo.

bro I can’t edit or reply in this post idk let me create another post can you close this one?

What do you mean? Are you having problems sharing code?

Have you understood the difference between the screenshots above?

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

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

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

You may need to toggle this. Make sure M is highlighted not A

type or paste code herelet currentArray = [];

function generateElement() {
  return Math.floor(Math.random() * 100) + 1;
}

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

function generateContainer() {
  return document.createElement("div");
}

function fillArrContainer(container, arr) {
  container.innerHTML = "";

  arr.forEach(num => {
    const span = document.createElement("span");
    span.textContent = num;
    container.appendChild(span);
  });
}

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

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

function highlightCurrentEls(container, index) {
  const children = container.children;

  if (index < children.length) {
    children[index].style.border = "2px dashed red";
  }

  if (index + 1 < children.length) {
    children[index + 1].style.border = "2px dashed red";
  }
}

document.getElementById("sort-btn").style.display = "none";

document.getElementById("generate-btn").addEventListener("click",()=> {
  const arrayContainer = document.getElementById("array-container");
  arrayContainer.innerHTML = "";

  const startingArrayDiv = document.createElement("div");
  startingArrayDiv.id = "starting-array";
  arrayContainer.appendChild(startingArrayDiv);

  currentArray = generateArray();
  fillArrContainer(startingArrayDiv, currentArray);
  
  document.getElementById("sort-btn").style.display = "inline-block";
});

document.getElementById("sort-btn").addEventListener("click",()=> {
  if (currentArray.length === 0) return;

  const arrayContainer = document.getElementById("array-container");
  const startingArrayDiv = document.getElementById("starting-array");

  fillArrContainer(startingArrayDiv, currentArray);
  highlightCurrentEls(startingArrayDiv, 0);

  let arr = [...currentArray];
  const n = arr.length;
  let isFirstStep = true;
  let swapped;

  for (let i = 0; i < n - 1; i++) {
    swapped = false;
    
    for (let j = 0; j < n - i - 1; j++) {
      if (isFirstStep) {
        isFirstStep = false;
        swapElements(arr, j);
        if (!isOrdered(arr[j], arr[j + 1])) {
          swapped = true;
        }
        continue;
      }

      const stepContainer = generateContainer();
      fillArrContainer(stepContainer, arr);
      highlightCurrentEls(stepContainer, j);
      arrayContainer.appendChild(stepContainer);

      const beforeSwap = arr[j];
      swapElements(arr, j);
      
      if (arr[j] !== beforeSwap) {
        swapped = true;
      }
    }
    
    if (!swapped) {
      break;
    }
  }

  const finalContainer = generateContainer();
  fillArrContainer(finalContainer, arr);
  finalContainer.style.border = "3px solid green";
  arrayContainer.appendChild(finalContainer);
  
  document.getElementById("sort-btn").style.display = "none";
});

nope still can’t point out whats wrong

nope can you explain?

Did you look at the screenshots? It’s kind of like a “find the difference game”.

Can you see the difference in what happens?

Did you read how the algorithm should work?

You can reply here if you need help. Please don’t open duplicate topics

Here’s a test you can try: Use the example app to get some output and screenshot that.

Then take the array that was generated in that example and hardcode it into your app, and sort it.

Then you can clearly see the different paths each app takes.