Bubble sort in list

2

I'm trying to sort a simple linked list, but I'm not getting it, it only changes the first node because the value is smaller, the rest does not change.

void ordenar(lista **l) {

    int tam = tamanho((*l));
    lista *prev, *current = (*l)->prox;

    for(int i=0; i<tam - 1; i++) {
        prev = *l;
        for(int j=0; j<tam; j++) {
            if(prev->data > current->data) {
                troca(prev, current);
            }
            current = prev->prox;
        }
        prev = prev->prox;
    }
}
    
asked by anonymous 19.04.2017 / 23:39

1 answer

1

The current = (*l)->prox must be within the first loop to restart every time.

The prev = prev->prox must be within the second loop to move through the list.

And current = prev->prox must be changed to current = current->prox to continue scrolling through the list.

As current already starts with the second element, the second loop for must go to tam-1 to not access a non-existent element.

void ordenar(lista **l) {

    int tam = tamanho((*l));
    lista *prev, *current;

    for(int i=0; i<tam - 1; i++) {
        prev = *l;
        current = (*l)->prox;
        for(int j=0; j<tam -1; j++) {
            if(prev->data > current->data) {
                troca(prev, current);
            }
            current = current->prox;
            prev = prev->prox;
        }
    }
}

I believe that this should be working, test your code and see if it is OK or if something is still wrong.

    
20.04.2017 / 01:05