Advertisement
juanjo12x

Bubble_Sort_Linked_List

May 19th, 2014
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.08 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct nodo{
  5.   int valor;
  6.   struct nodo* ptrSig;
  7. }TNodo;
  8.  
  9. int lista_vacia(TNodo *);
  10. void inserta_inicio(TNodo **, int);
  11.  
  12. void imprime_lista(TNodo *);
  13. void libera_lista(TNodo *);
  14. void bubbleSort(TNodo *);
  15.  
  16. void inserta_inicio(TNodo **ptrListaSE, int valor){
  17.     TNodo *ptrNuevo;
  18.     ptrNuevo = (TNodo*)malloc(sizeof(TNodo));
  19.     ptrNuevo->valor = valor;
  20.     ptrNuevo->ptrSig = *ptrListaSE;
  21.     *ptrListaSE = ptrNuevo;
  22. }
  23.  
  24. int lista_vacia(TNodo * ptrListaSE){
  25.     return ptrListaSE==NULL;
  26. }
  27.  
  28. void imprime_lista(TNodo * ptrListaSE){
  29.     while (ptrListaSE != NULL){
  30.         /*printf(" %d ", (*ptrListaSE).valor);*/
  31.         printf(" %d ", ptrListaSE->valor);        
  32.         ptrListaSE = ptrListaSE->ptrSig;
  33.     }
  34.     printf("NULL\n");
  35. }
  36.  
  37. void libera_lista(TNodo * ptrListaSE){    
  38.     TNodo * ptrEliminar;
  39.     while (ptrListaSE != NULL){
  40.         ptrEliminar = ptrListaSE;                
  41.         ptrListaSE = ptrListaSE->ptrSig;
  42.         free(ptrEliminar);
  43.     }    
  44. }
  45. /* function to swap data of two nodes a and b*/
  46. void swap(TNodo *a, TNodo *b)
  47. {
  48.     int temp = a->valor;
  49.     a->valor = b->valor;
  50.     b->valor = temp;
  51. }
  52. void bubbleSort(TNodo *ptrListaSE)
  53. {
  54.     int swapped, i;
  55.     TNodo *ptr1;
  56.     TNodo *lptr = NULL;
  57.  
  58.     /* Lista Vacia? */
  59.     if (ptr1 == NULL)
  60.         return;
  61.  
  62.     do
  63.     {
  64.         swapped = 0;
  65.         ptr1 =ptrListaSE;
  66.  
  67.         while (ptr1->ptrSig != lptr)
  68.         {
  69.             if (ptr1->valor > ptr1->ptrSig->valor)
  70.             {
  71.                 swap(ptr1, ptr1->ptrSig);
  72.                 swapped = 1;
  73.             }
  74.             ptr1 = ptr1->ptrSig;
  75.         }
  76.         lptr = ptr1;
  77.     }
  78.     while (swapped);
  79. }
  80. int main(int argc, char** argv) {
  81.     TNodo * ptrListaSE = NULL;
  82.     TNodo * ptrUltimo = NULL;
  83.     inserta_inicio(&ptrListaSE, 19);
  84.     inserta_inicio(&ptrListaSE, 15);
  85.     inserta_inicio(&ptrListaSE, 17);
  86.     inserta_inicio(&ptrListaSE, 20);
  87.     bubbleSort(ptrListaSE);
  88.     imprime_lista(ptrListaSE);
  89.     libera_lista(ptrListaSE);
  90.     return (EXIT_SUCCESS);
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement