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

135
Visualizações
Bubble sort didn't sort

I tried to do bubble sort and still a beginner, I didn't find any errors but when I tried to sort it alphabetically it didn't sort the array.

public class Main  {

    public static void bubblesort ( String [] name) {
        String tempmemory = " na";

        for (int i = 0; i < name.length; i++) {
            for (int j = 0; j < (name.length - 1); j++) {

                if (name[j].compareTo(name[j + 1]) < 0)

                    tempmemory = name[j];
                name[j] = name[j + 1];
                name[j + 1] = tempmemory;
            }
        }
    }

    public static void main ( String [] args) {

        String [] name  = { "ciku", "eman","aina"} ;

        int i=0;

        System.out.println(" Before sort : ");
        while (i < name.length)
        {
            System.out.print ( name[i] + "  ");

            i++;
        }

        bubblesort(name);

        i=0;
        System.out.println(" \n After sort : ");
        while (i < name.length)
        {
            System.out.print ( name[i] + "  ");

            i++;
        }

}


}

How can I fix this code to correctly sort an array using bubble sort?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Your if condition should include those 3 statements, right now it only have one statement under it i.e tempmemory = name[j];. So use {} bracket for if condition if it has multiple statement. So write if statement like this:

if (name[j].compareTo(name[j + 1]) < 0) {
    tempmemory = name[j];   
    name[j] = name[j + 1];
    name[j + 1] = tempmemory; 
}
over 4 years ago · Santiago Trujillo Relatório

0

This chunk of code:

            if (name[j].compareTo(name[j + 1]) < 0)

                tempmemory = name[j];
            name[j] = name[j + 1];
            name[j + 1] = tempmemory;

is obviously wrong.

Hint: use { and } to fix it.

over 4 years ago · Santiago Trujillo 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