3
I am playing a sorting algorithm by selection using chained list.
I’m using two loops using a min cell, i and j, with respect to cell j, ok, but at the time of changing the min pointers and i is not working, when I change the two, i starts the loop at the position that would previously be min, however when having cause i point again to previous position and start the loop in what would be the position i->prox
I am not succeeding without getting lost in the pointers. I have tried auxiliary cells, auxiliary variables, boolean variables and there was no evolution.
Detail: I cannot create cell vectors or linked auxiliary lists.
Code below:
#include<stdio.h>
#include<stdlib.h>
struct cel {
int cont;
struct cel *prox;
};
typedef struct cel celula;
void insere (int x, celula *p) {
celula *nova;
nova = NULL;
nova = (celula *)malloc (sizeof (celula));
nova->cont = x;
nova->prox = p->prox;
p->prox = nova;
}
void selectsort(celula *p) {
celula *ai, *i, *aj, *j, *min, *amin, *pmin;
ai = p;
i = p->prox;
while (i != NULL) {
aj = i;
j = i->prox;
min = i;
while(j != NULL) {
if (j->cont < min->cont) {
amin = aj; min = j, pmin = j->prox;
}
aj = j;
j = j->prox;
}
if (i->cont > min->cont) {
min->prox = i->prox;
ai->prox = min;
i->prox = pmin;
amin->prox = i;
}
ai = i;
i = i->prox;
}
}
void imprima (celula *p) {
celula *v;
for (v = p->prox; v != NULL; v = v->prox)
printf ("%d ", v->cont);
printf("\n");
}
int main () {
celula *l = malloc (sizeof (celula));
l->prox = NULL;
insere(7, l);
insere(11, l);
insere(8, l);
insere(4, l);
insere(12, l);
insere(9, l);
insere(1, l);
imprima(l);
selectsort(l);
printf("\n");
imprima(l);
return 0;
}
Thanks for the answer, I hadn’t tried that way, that code I posted was a test with integers. The idea would be to change the positions using the same pointers pq in the cell struct, in the work I’m doing, I will have more than one variable to change, are two char, two integers and a double, if using with swap will be immense conditions, I will have to change one by one, have idea how change using only the pointers to avoid these exchanges?
– Marcelo de Sousa
So I changed the code to swap on struct pointers !!! A strong hug!
– Rodrigo Alves Guerra
Thanks man... Thanks a lot, you helped a lot.
– Marcelo de Sousa