Guarda questo se vuoi vedere è tutto il codice
codice:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct linked{
int value;
struct linked *next;
} *first = NULL, *new;
void add(int);
void show(void);
struct linked * merge(struct linked *, struct linked *);
struct linked *mergesort(struct linked *);
void main(){
add(25);
show();
first = mergesort(first);
show();
}
void add(int nr){
srand(time(NULL));
while(nr--){
if(!(new = (struct linked *)malloc(sizeof(struct linked))))
abort();
(*(new)).value = rand()%100;
(*(new)).next = NULL;
(*(new)).next = first;
first = new;
}
}
struct linked * merge(struct linked *a, struct linked *b){
struct linked head;
struct linked *node = &head;
while((a != NULL) && (b != NULL))
if(a->value <= b->value){
node->next = a;
node = a;
a = a->next;
}
else{
node->next = b;
node = b;
b = b->next;
}
node->next = (a == NULL) ? b : a;
return head.next;
}
struct linked *mergesort(struct linked *node){
struct linked *a = node;
struct linked *b = node->next;
if(node == NULL || node->next == NULL)
return node;
while((b != NULL) && (b->next != NULL)){
node = node->next;
b = b->next;
}
b = node->next;
node->next = NULL;
return merge(mergesort(a), mergesort(b));
}
void show(){
struct linked *temp;
for(temp = first; temp->next != NULL; temp = temp->next)
printf("%d ", temp->value);
printf("\n");
}