Bubble Sort in list

Asked

Viewed 2,197 times

2

I’m trying to order a simple chained list, but I’m not succeeding, 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;
    }
}

1 answer

1


The current = (*l)->prox must be inside the first loop to start over every time.

The prev = prev->prox must be inside the second loop to go through the list.

And the current = prev->prox must be exchanged for current = current->prox to continue browsing the list.

Like the current already begins with the second element, the second loop for should go up to tam-1 not to 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 this should be working, test your code and see if it’s OK or if there’s still something wrong.

  • why the second goes up to < pos - 1, and last element?

  • Because Prev starts at the first element and Current at the second. If you do not place post-1, at the end of the for Prev will go to last element and Current will access an element that does not exist and cause error.

  • With the post-1 the Prev will go to the penultimate and Current to the last, making the exchanges normally.

  • 1

    ah, now I get it. I made a version without using the for. It became more readable. https://pastebin.com/1qXNb8ps

Browser other questions tagged

You are not signed in. Login or sign up in order to post.