I need to use the Quicksort sorting algorithm to sort elements of a linked list. It is important to note that I must not just swap the key values, but the elements themselves. My code simply does not work; I believe I am making a mistake with the recursion. I would like a solution.
I created the following functions to achieve my goal:
///QUICK SORT///
struct elemento *particiona(struct elemento *ini, struct elemento *fim){
struct elemento *pivo, *aux, *t1, *t2, *t3, *teste;
t1 = ini;
t2 = ini;
teste = ini;
int flag = 0;
/*printf("nini = %dn", ini->chave[0]);
printf("nfim = %dn", fim->chave[0]);*/
for(pivo = aux = ini; aux && aux != fim; ) {
if(aux->chave[0] < fim->chave[0]){
if(ini != aux){
pivo = aux;
flag = 1;
if(t1 == ini){
if(t1 != t2){
teste = aux;
ini = ini->prox;
t1->prox = aux->prox;
aux->prox = ini;
t2->prox = t1;
t1 = aux;
aux = t2->prox->prox;
}
else if(t1 == t2){
teste = aux;
aux = aux->prox;
t1 = t1->prox;
t1->prox = ini;
ini->prox = aux;
}
}
else{
t1->prox = aux; //10 liga no 5
aux = aux->prox; //aux 20
t1->prox->prox = ini->prox; //5 liga no 40
t2->prox = ini; //10 liga no 50
ini = ini->prox; //ini 40
t2->prox->prox = aux;
}
}
else{
ini = ini->prox;
}
}
if(flag == 0)
aux = aux->prox;
if(t1 != ini && t1->prox != ini){
t1 = t1->prox;
}
if(t2 != aux && t2->prox != aux)
t2 = t2->prox;
flag = 0;
}
t1->prox = fim; //50 liga no 20
t3 = fim->prox; //NULL
t1->prox->prox = ini->prox; //5 liga no 40
t2->prox = ini; //10 liga no 50
ini->prox = t3;
fim = ini;
ini = aux;
printf("npivo = %dn", pivo->chave[0]);*/
mostrar_chaves(teste);
return pivo;
}
void quick_sort(struct elemento *ini, struct elemento *fim){
struct elemento *pivo;
printf("nINI_Q - %d FIM_Q - %dn",ini->chave[0], fim->chave[0]);
if (ini == fim) {
printf("nreturn estado anteriorn");
return;
}
pivo = particiona(ini, fim);
if (pivo && pivo->prox) {
quick_sort(pivo->prox, fim);
}
if (pivo && ini != pivo) {
quick_sort(ini, pivo);
}
}
struct elemento *fim(struct elemento *ini){
struct elemento *fim;
for(fim = ini; fim && fim->prox; fim = fim->prox);
return fim;
}
New contributor
Besouro Branco is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.