You know, it's hard to answer that question. I understand that sorting is the most primitive.for(i=0; i<n; i++)
for(j=i+1; j<n; j++)
...
In many cases, it's worse than bubble, but it's not that. I couldn't understand the logic of swap. Too hard. All it requires is to change the p-articled and q-articled values. For example:swap(list_ *p, lisp_ *q) {
rec w;
memcpy(&w, &p->d, sizeof(rec));
memcpy(&p->d, &p->q, sizeof(rec));
memcpy(&p->q, &w, sizeof(rec));
}
If I didn't lie.
If you don't want to move rec d, and if you want only to replace the indexes, you'll see that the first element will be moved, that is. You'll have to have a empty head with an unfilled field (d) to change the index to the first element. And the indexes for the preceding elements should not be searched in swap (this is an extra calculation) but should be taken out of sortlist (this can be compared not p-d from q-bed, but p-next-d from q-next-stated). That's it.Also. Your assertions look pretty suspicious. There's a clear mistake.Added:
The empty head is just a copy of the list_, the field d is not used. One element needs a list of 2, 2 l, a list of three, etc.
Processing begins with p = p0 and ends when p-nationalnext == sync, corrected by elderman == @elder_manlist_ *sortlist (list_ *p0, reccmp_f comp) {
list *q, *p;
for (p=p0; p->next != 0; p = p->next)
for (q=p->next; q->next != 0; q=q->next)
if (comp(&q->next->d, &p->next->d)) swap(p, q);
}
void swap(list_ *p, list_ *q) {
list_ *w;
w = p->next;
p->next = q->next;
q->next = w;
w = p->next->next;
q->next->next = p->next->next;
p->next->next = w;
}
Added after comment @avp. The last text is bullshit. Thank you. You can't do that with the contact lists, the structure collapses. I apologize.Another addition. It's a bubble, as well as an empty head. On the picture, an explanation of how the liquors are moving when crossing the neighbouring elements (with p-next and q-next addresses). It's the original version, and it's a bad idea. Well, it's definitely not a match list.
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int num;
char name[20];
} rec;
typedef struct list {
rec d;
struct list * next;
} list_;
typedef int reccmp_f (rec *r1, rec *r2);
int isRec_Num (rec *r1,rec *r2) {
return r1->num<r2->num;
}
list_ *sortlist (list_ *p0, reccmp_f *comp) {
list_ *q, *p, *w;
int wasExchange;
do {
wasExchange = 0;
for (p=p0; p->next->next != 0; p = p->next) {
q = p->next;
if ((*comp) (&q->next->d, &p->next->d)) {
w=q->next;
q->next=q->next->next;
w->next=q;
p->next = w;
wasExchange = 1;
//p=q;
}
}
} while (wasExchange);
return p0;
}
int main() {
list_ *l = malloc(sizeof(list_));
int i, nums[] = {1, 4, 2, 4, 6, 3};
list_ *p;
for (i=0, p=l; i < sizeof nums/sizeof(int); i++) {
p->next = malloc(sizeof(list_));
p=p->next;
p->d.num = nums[i];
}
p->next = 0;
sortlist(l, &isRec_Num);
for(p=l; p->next; p=p->next)
printf("%d\n", p->next->d.num);
}