Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

109
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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++)

about 4 years ago · Juan Pablo Isaza Relatório

0

Problem is here, 'j + 1' is out of bounds for array and it will be undefined

childElements[j + 1].style.backgroundColor = "red";
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda