Advertisement
rihardmarius

bubble sort - listas

Dec 7th, 2013
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct node {
  5.   int entry = 0; // valores por defecto
  6.   node *next = nullptr;
  7. };
  8.  
  9. struct lista {
  10.     node* root = nullptr;
  11. };
  12.  
  13. void mostrar_lista (lista& l) // funciona
  14. {
  15.     for (node *p = l.root; p != 0; p = p->next)
  16.         cout << p->entry << ' ';
  17.     cout << endl << endl;
  18. }
  19.  
  20. void insertar_nodo_al_final (lista &l, int a) // funciona
  21. {
  22.     node* nuevo = new node;
  23.     nuevo->entry = a;
  24.     if (l.root != 0) // apunta a algo?
  25.     {
  26.         node* p = l.root;
  27.         while (p->next != 0)
  28.             p = p->next;
  29.         p->next = nuevo;
  30.     }
  31.     else
  32.         l.root = nuevo;
  33. }
  34.  
  35. void swap_entries (node*& a, node*& b)
  36. {
  37.     int aux = a->entry;
  38.     a->entry = b->entry;
  39.     b->entry = aux;
  40. }
  41.  
  42. void bubble_sort (lista& a)
  43. {
  44.     node* p; node* q; bool swapped = true;
  45.  
  46.     while (swapped)
  47.     {
  48.         swapped = false;
  49.         p = a.root;
  50.         q = a.root;
  51.         q = q->next;
  52.  
  53.         while (q != 0)
  54.         {
  55.             if (p->entry > q->entry)
  56.             {
  57.                 swap_entries (p,q);
  58.                 swapped = true;
  59.             }
  60.             p = p->next;
  61.             q = q->next;
  62.         }
  63.     }
  64. }
  65.  
  66. int main()
  67. {
  68.     lista L;
  69.  
  70.     for (int i=10; i>0; i--)
  71.         insertar_nodo_al_final (L, (i+3)%10);
  72.  
  73.     mostrar_lista(L);
  74.  
  75.     bubble_sort(L);
  76.  
  77.     mostrar_lista(L);
  78.  
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement