'Bubble Sort visualizer not showing expected outcome
I am creating a bubble sort visualizer using html, css and javascript. Following is the javascript code:
const numbers = [];
let targetParent = document.querySelector("#bars")
function swap(el1, el2) {
const style1 = window.getComputedStyle(el1);
const style2 = window.getComputedStyle(el2);
const transform1 = style1.getPropertyValue("height");
const transform2 = style2.getPropertyValue("height");
el1.style.height = transform2;
el2.style.height = transform1;
}
function bubbleSort() {
let childElements =targetParent.children;
console.log(childElements);
for (let i = 0; i < numbers.length; i++) {
for (let j = 0; j < numbers.length - i; j++)
{
childElements[j].style.backgroundColor = "red";
childElements[j + 1].style.backgroundColor = "red";
if (numbers[j] > numbers[j + 1]) {
let temp=numbers[j];
numbers[j]=numbers[j+1];
numbers[j+1]=temp;
swap(childElements[j], childElements[j + 1]);
}
}
childElements[n - i].style.backgroundColor = "green";
}
}
function createArray() {
numbers.splice(0, numbers.length);
targetParent.innerHTML = "";
while (numbers.length < 100) {
let r = Math.floor(Math.random() * 100);
numbers.push(r);
}
console.log(numbers);
let element = document.createElement("div");
element.classList.add("bar");
element.style.width = "10px";
element.style.backgroundColor = "yellow";
element.style.border = "1px solid";
for (let i = 0; i < 100; i++) {
element.style.height = `${numbers[i] * 3}px`;
targetParent.appendChild(element.cloneNode(true));
}
let buttons = document.getElementsByClassName("sortbtn");
Array.from(buttons).forEach((element) => {
element.disabled = false;
})
}
It creates random numbers from 1 to 100, creates respective div tags to represent the numbers and then sorts them using bubble sort. But I don't know why I am not getting the sorted result. It also shows the following error:
Uncaught TypeError: Cannot read properties of undefined (reading 'style')
This error occurs at this line:
childElements[j].style.backgroundColor = "red";
But when I console.log(childElements), it successfully shows the created div tags to represent the numbers.
Please can someone help me out. Thanks in advance.
Solution 1:[1]
Problem is here, 'j + 1' is out of bounds for array and it will be undefined
childElements[j + 1].style.backgroundColor = "red";
Solution 2:[2]
When i is 0 and j is 9 then j+1 refers to childElements[10] which isn't defined.
Try changing the second for loop to
for (let j = 0; j < numbers.length - i - 1; j++)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Siva K V |
| Solution 2 | Bastis |
