Tell us what’s happening:
can someone help i cant pass 18th and 19th step and have tried multiple times
Your code so far
<!-- file: index.html -->
```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, i) {
if (!isOrdered(arr[i], arr[i + 1])) {
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
}
}
function highlightCurrentEls(container, index) {
const children = container.querySelectorAll('span');
if (children[index]) {
children[index].style.border = '2px dashed red';
}
if (children[index + 1]) {
children[index + 1].style.border = '2px dashed red';
}
}
// DOM Elements
const generateBtn = document.getElementById('generate-btn');
const sortBtn = document.getElementById('sort-btn');
const arrayContainer = document.getElementById('array-container');
const startingArray = document.getElementById('starting-array');
let currentArray = [];
generateBtn.addEventListener('click', () => {
// Clear all except #starting-array
Array.from(arrayContainer.children).forEach(child => {
if (child.id !== 'starting-array') child.remove();
});
// Generate and fill array
currentArray = generateArray();
fillArrContainer(startingArray, currentArray);
});
sortBtn.addEventListener('click', () => {
if (currentArray.length === 0) return;
// Clear all previous sorting steps except #starting-array
Array.from(arrayContainer.children).forEach(child => {
if (child.id !== 'starting-array') child.remove();
});
// Highlight first 2 elements in #starting-array
highlightCurrentEls(startingArray, 0);
// Bubble Sort steps
const arr = [...currentArray];
const steps = [];
// Push initial array state
steps.push({ state: [...arr], index: 0 });
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
steps.push({ state: [...arr], index: j });
swapElements(arr, j);
}
}
// Final sorted state
steps.push({ state: [...arr], index: -1 }); // No highlight
// Render each step (excluding #starting-array)
steps.forEach((step, idx) => {
// Skip the first step — already shown in #starting-array
if (idx === 0) return;
const stepDiv = generateContainer();
fillArrContainer(stepDiv, step.state);
if (step.index >= 0) {
highlightCurrentEls(stepDiv, step.index);
}
arrayContainer.appendChild(stepDiv);
});
});
```css
/* file: styles.css */
/* file: script.js */
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36
Challenge Information:
Build a Sorting Visualizer - Build a Sorting Visualizer