Search code examples
cbubble-sortc-strings

Bubble sort algorithm in an array of strings runs with no erros, but does nothing


It's supposed to sort the 30 names in nombres in alphabetical order, the function burbuja() executes, but after it finishes all the names are still unsorted

#include <string.h>
#include <stdio.h>

#define max 30

int mostrar(char nombres[max][80])
{
    int i;
    printf("\nLa pila ahora tiene los siguentes elementos\n");
    for(i = 0; i < max; i++)
        printf("%s\n",nombres[i]);
}

void burbuja(char nombres[max][80]) //part that does not work
{
    int i, j;
    char aux[80];
    for (i = 0; i < max; i++)
    {
        for (j = i + 1; j < max - i - 1; j++)
        {
            if(nombres[j - 1] > nombres[j])
            {
                strcpy(aux, nombres[j - 1]);
                strcpy(nombres[j - 1], nombres[j]);
                strcpy(nombres[j], aux);
            }
        }
    }
}

int main()
{
    char nombres[30][80] = {
        "Javier", "Paola", "Paco", "Pedro", "Jorge", "Luis", "Champ",
        "Alma", "Alicia", "Stephanie", "Mark", "Daniel", "Hank", "Malcom",
        "Jaime", "Luisa", "Lila", "Beatriz", "Teresa", "Maria", "Michel", 
        "Karina", "Karen", "Carmen", "Juan", "Daniela", "Ana", "Gavin",
        "Rosa", "Francisco"
    };

    mostrar(nombres);
    burbuja(nombres);
    mostrar(nombres);
}

it show correctly the names unsorted, bubble function does the thing, then it show all the same names still unsorted

...Program finished with exit code 0
Press ENTER to exit console


Solution

  • In nombres[j - 1] > nombres[j], both nombres[j-1] and nombres[j] are character arrays. And an array name by itself decays into a pointer to the first element of that array.

    So by nombres[j - 1] > nombres[j], you are merely comparing the pointers to the first element of the two arrays.

    You need a function like strcmp().

    And for (j = i + 1; j < max - i - 1; j++) won't cover the whole array properly.

    Try something like

    for (i=0; i<max; i++)
    {
        for (j=0; j<max-1-i; j++)
        {
            if(strcmp(nombres[j], nombres[j+1])>0)
            {
                strcpy(aux, nombres[j]);
                strcpy(nombres[j], nombres[j+1]);
                strcpy(nombres[j+1], aux);
            }
        }
    }
    

    strcmp() returns a value greater than zero if the first string comes after the second in lexicographical order.

    Edit:

    As David C. Rankin pointed out, you could make the return type of the mostrar() function to void as you are not returning any value.