Build a Sorting Visualizer - Build a Sorting Visualizer

Tell us what’s happening:

Hey what’s wrong here?

Your code so far

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

/* file: styles.css */

/* file: script.js */

Your browser information:

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

Challenge Information:

Build a Sorting Visualizer - Build a Sorting Visualizer

Your code didn’t come through. Would you post it please?

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Bubble Sort Visualizer</title>

<link rel="stylesheet" href="styles.css">

</head>

<body>

<h1>Bubble Sort Visualizer</h1>

<div id="array-container">

<div id="starting-array"></div>

</div>




<button id="generate-btn">Generate Array</button>

<button id="sort-btn">Sort Array</button>




<script src="script.js"></script>

</body>

</html>
body {

    font-family: Arial, sans-serif;

display: flex;

flex-direction: column;

align-items: center;

margin-top: 50px;

}




#array-container {

display: flex;

flex-direction: column;

gap: 10px;

margin-bottom: 20px;

}




#array-container div {

display: flex;

gap: 5px;

padding: 5px;

border: 1px solid #ccc;

border-radius: 5px;

background-color: #f9f9f9;

}




span {

display: inline-block;

width: 30px;

height: 30px;

line-height: 30px;

text-align: center;

border: 1px solid #333;

background-color: white;

border-radius: 3px;

font-weight: bold;

}




button {

margin: 5px;

padding: 10px 20px;

font-size: 16px;

cursor: pointer;

}


/* 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 = "";

// FIXED: Using createElement and appendChild for robustness in test environments

for (let i=0; i<arr.length; i++) {

const span = document.createElement("span");

span.textContent = arr[i].toString();

eltHTML.appendChild(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) => {

// First, remove existing highlights from all children in the container

const childElements = eltHTML.children;

for (let i = 0; i < childElements.length; i++) {

childElements[i].style.border = '1px solid #333'; // Reset to default

  }

// Apply the required highlight

if (childElements[index]) {

childElements[index].style.border = '2px dashed red';

  }

if (childElements[index + 1]) {

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", () => {

// Requirement 17: Remove all other elements from arrayContainer

const toRemove = arrayContainer.querySelectorAll(

':not([id="starting-array"])');

toRemove.forEach(element => {element.remove();}); 

sortArr = generateArray();

fillArrContainer(startingArr, sortArr);

// Ensure the starting array is not highlighted after generation

highlightCurrentEls(startingArr, -1);

});




/* 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");




// REORGANIZED AND CORRECTED LISTENER

sortBtn.addEventListener("click", () => {

if (!sortArr || sortArr.length === 0) {

// Prevent sorting if array hasn't been generated

return;

  }

// 1. Cleanup and Setup (Ensures #starting-array is the only child initially)

const toRemove = arrayContainer.querySelectorAll(

':not([id="starting-array"])');

toRemove.forEach(element => { element.remove(); }); 




// Use a fresh copy to sort

let tempArr = [...sortArr];

const n = tempArr.length;

let stepCount = 0;

// Refill the starting array content (crucial if generate was not clicked immediately before sort)

fillArrContainer(startingArr, sortArr);

// --- Bubble Sort Visualization: One DIV per Comparison Step (Meeting Req 18) ---

// Outer loop (passes)

for (let i = 0; i < n; i++) {

// Inner loop (comparisons)

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

let container;




// 2. DETERMINE CONTAINER

if (stepCount === 0) {

// Use existing #starting-array for the first step (Req 21)

container = startingArr; 

      } else {

// Create new container for all subsequent steps (Req 18 count)

container = generateContainer();

// Visualize the array state *before* the comparison/swap

fillArrContainer(container, tempArr); 

arrayContainer.appendChild(container);

      }

// 3. VISUALIZE: Highlight the pair being compared (j and j+1)

highlightCurrentEls(container, j);




// 4. ALGORITHM: Perform the comparison and swap logic

swapElements(tempArr, j);

stepCount++;

    }

  }




// 5. FINAL STATE: Display final sorted array (Req. 18)

const finalDiv = generateContainer();

finalDiv.id = "sorted-array"; 

fillArrContainer(finalDiv, tempArr);

// Remove highlights from the final state

highlightCurrentEls(finalDiv, -1); 

arrayContainer.appendChild(finalDiv);

});

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.

Apparently something is incorrect with the btn.

For this lab, you have been provided with all the HTML and CSS. You will use JavaScript to complete the Bubble Sort Visualizer so that it visualizes each step needed by the Bubble Sort algorithm to sort an array of five integers.

The first thing I notice is that your HTML and CSS do not match the given code. I suggest copying your JS and resetting this step to get the original HTML and CSS back. Then paste your JS back in.

Ok thank you very much.

It’s still coming up with the same 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.

There must be a bug which restricts me from passing this challenge.

Yes. Please carefully read this instruction again.

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.

If you test in the preview, you’ll see that each pass after the first highlights one less pair.

You’ll also notice that your code does not stop after a cycle completes with no swaps.

What needs changing for these functions? I’m previewing however its not continous.

Its just not working.

I don’t understand. What is not continuous?

Can you resend your response?

I made the test but still doesn’t work. I think I’m missing something.

What have you done so far to try to debug your code?

I’ve tested the algorithms sort button as instructed but it’s still blacking out no reaction. I’m still stuck on step 18. Can you upload a snippet to help if possible it’s correct code only problem is the bugging out.

Have you tried logging inside your code to see what’s going on?

And if you’re having trouble seeing where your solution differs from what’s expected, you can compare what the example generates to what your code generates. For example, the following screenshot is from the example app.

To test, I commented out the call to generateArray() in the “Generate” button listener in your code and hardcoded the same array to see how your code compares:

This should give you a clearer picture of what you need to work on in your code and where you may need to log variables to make sure they are what you expect.

I’m still stuck bud any further hints or solutions :joy: ?

Looking at the buttons displayed in the example app and your code, what is different? Try clicking the “Sort” button in your code again after the array is sorted. Should your code behave that way? This can be easily fixed.

What can you change in your code to break out of the loop after there have been no swaps during a cycle through the array? Look at what you can change in an existing function to help you with that.

What can you change in your code to make sure each pair of numbers in your array is checked to see if they should be swapped?

Take it a step at a time. Log variables or conditions in your code so you can see if their values are what you expect.

Good luck.

I’m trying with no luck do you want to check my code again?