fork download
  1. #include <iostream>
  2.  
  3. // This is a quick node struct with underlying integral data type.
  4. struct Node
  5. {
  6. int Data;
  7. Node* Link;
  8.  
  9. Node(int data, Node* link)
  10. {
  11. Data = data;
  12. Link = link;
  13. }
  14. };
  15.  
  16. // This is the function that swaps two nodes. Its parameters are
  17. // addresses of pointers that point to the elements to be swapped.
  18. void node_swap(Node** a, Node** b)
  19. {
  20. Node* a1 = *a;
  21. Node* a2 = a1->Link;
  22.  
  23. Node* b1 = *b;
  24. Node* b2 = b1->Link;
  25.  
  26. b1->Link = a1;
  27. a1->Link = b2;
  28.  
  29. *a = b1;
  30. }
  31.  
  32. int main()
  33. {
  34. // This is a quick linked list that is obviously unsorted.
  35. Node z(67, nullptr);
  36. Node y(49, &z);
  37. Node x(55, &y);
  38. Node w(60, &x);
  39. Node v(78, &w);
  40. Node u(77, &v);
  41. Node t(10, &u);
  42. Node s(69, &t);
  43. Node r(82, &s);
  44. Node q(28, &r);
  45. Node p(29, &q);
  46. Node o(27, &p);
  47. Node n(14, &o);
  48. Node m(95, &n);
  49. Node l(91, &m);
  50. Node k(79, &l);
  51. Node j(31, &k);
  52. Node i( 3, &j);
  53. Node h(37, &i);
  54. Node g(76, &h);
  55. Node f(99, &g);
  56. Node e(65, &f);
  57. Node d(19, &e);
  58. Node c(64, &d);
  59. Node b(35, &c);
  60. Node a(51, &b);
  61.  
  62. Node* head = &a;
  63.  
  64. // This is to display the entire linked list.
  65. std::cout << "Unsorted: ";
  66.  
  67. for (Node* t = head; t != nullptr; t = t->Link)
  68. {
  69. std::cout << t->Data << ' ';
  70. }
  71.  
  72. std::cout << std::endl;
  73.  
  74. // This is the bubble sort algorithm.
  75. bool has_swapped;
  76.  
  77. do
  78. {
  79. has_swapped = false;
  80.  
  81. for (Node** t = &head; (*t)->Link != nullptr; t = &(*t)->Link)
  82. {
  83. if ((*t)->Data > (*t)->Link->Data)
  84. {
  85. node_swap(t, &(*t)->Link);
  86. has_swapped = true;
  87. }
  88. }
  89. } while (has_swapped);
  90.  
  91. // This is to display the entire linked list.
  92. std::cout << " Sorted: ";
  93.  
  94. for (Node* t = head; t != nullptr; t = t->Link)
  95. {
  96. std::cout << t->Data << ' ';
  97. }
  98.  
  99. std::cin.get();
  100.  
  101. return 0;
  102. }
Success #stdin #stdout 0s 3300KB
stdin
Standard input is empty
stdout
Unsorted: 51 35 64 19 65 99 76 37 3 31 79 91 95 14 27 29 28 82 69 10 77 78 60 55 49 67 
  Sorted: 3 10 14 19 27 28 29 31 35 37 49 51 55 60 64 65 67 69 76 77 78 79 82 91 95 99