juaniisuar

M E R G E B O I S

Jul 5th, 2017
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. typedef struct _SNodo {
  6. int d;
  7. struct _SNodo *sig;
  8. } SNodo;
  9.  
  10. typedef SNodo *SList;
  11.  
  12. SList SList_new(){
  13. return NULL;
  14. }
  15.  
  16. SList SList_add(SList lista, int d){
  17. SList k = malloc(sizeof(SNodo));
  18. k->d = d;
  19. k->sig = lista;
  20.  
  21. return k;
  22. }
  23.  
  24. int SList_size(SList lista){
  25. int cont;
  26. SNodo *aux = lista;
  27. for(cont=0; aux; cont++, aux=aux->sig);
  28.  
  29. return cont;
  30. }
  31.  
  32. void SList_particionar(SList lista, SList *LI, SList *LD){
  33. int i, n = SList_size(lista);
  34. (*LI) = lista;
  35.  
  36. for(i=0; i<(n-1)/2; i++)
  37. lista=lista->sig;
  38. (*LD) = lista->sig;
  39. lista->sig = NULL;
  40. }
  41.  
  42.  
  43. SList SList_fusionar(SList LI, SList LD){
  44. SList aux = malloc(sizeof(SNodo));
  45.  
  46. if(!LI) return LD;
  47. if(!LD) return LI;
  48.  
  49. SList temp, dummy = aux;
  50.  
  51. while(LI && LD){
  52. dummy->sig = malloc(sizeof(SNodo));
  53. dummy = dummy->sig;
  54. if(LI->d < LD->d){
  55. dummy->d = LI->d;
  56. dummy->sig = NULL;
  57.  
  58. temp = LI;
  59. LI = LI->sig;
  60. free(temp);
  61. } else {
  62. dummy->d = LD->d;
  63. dummy->sig = NULL;
  64.  
  65. temp = LD;
  66. LD = LD->sig;
  67. free(temp);
  68. }
  69. }
  70. if(LI && !LD) dummy->sig = LI;
  71. if(!LI && LD) dummy->sig = LD;
  72.  
  73. temp = aux;
  74. aux = aux->sig;
  75. free(temp);
  76.  
  77. return aux;
  78. }
  79.  
  80. SList mergesort(SList lista){
  81. if(SList_size(lista) <= 1) return lista;
  82.  
  83. SList Lizq, Lder;
  84. SList_particionar(lista, &Lizq, &Lder);
  85.  
  86. Lizq = mergesort(Lizq);
  87. Lder = mergesort(Lder);
  88.  
  89. return SList_fusionar(Lizq, Lder);
  90. }
  91.  
  92. void SList_print(SList lista){
  93. while(lista){
  94. printf("%d ", lista->d);
  95. lista = lista->sig;
  96. }
  97. puts("");
  98. }
  99.  
  100. int main(){
  101. int i;
  102. srand(time(NULL));
  103. SList L = SList_new();
  104.  
  105. for(i=0; i<15; i++)
  106. L = SList_add(L, rand()%1000+1);
  107. SList_print(L);
  108.  
  109. L = mergesort(L);
  110.  
  111. SList_print(L);
  112.  
  113. return 0;
  114. }
Add Comment
Please, Sign In to add comment