Advertisement
finalmail

queue-sort

Jul 28th, 2020
2,698
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <math.h>
  5. #include <vector>
  6. #include <string>
  7.  
  8. using namespace std;
  9.  
  10. struct node {
  11.     int value;
  12.     node* next;
  13.     node(int v) {
  14.         value = v;
  15.         next = nullptr;
  16.     }
  17. };
  18.  
  19. class myQ {
  20.     public:
  21.   node* first;
  22.   node* last;
  23.  
  24.   myQ() {
  25.       first = nullptr;
  26.       last = nullptr;
  27.   }
  28.  
  29.   void add(int value) {
  30.       node* newNode = new node(value);
  31.       if (!first) {
  32.           first = newNode;
  33.       }
  34.       if (!last) {
  35.           last = newNode;
  36.       } else {
  37.         last->next = newNode;
  38.         last = newNode;
  39.       }
  40.   }
  41. };
  42.  
  43. void sortQ(myQ* queToSort) {
  44.     node* it = queToSort->first;
  45.     for (node* i = queToSort->first; i->next != nullptr; i = i->next) {
  46.         bool swapped = false;
  47.         for (node* j = i->next; j != nullptr; j = j->next) {
  48.             if (i->value > j->value) {
  49.                 int tmp = j->value;
  50.                 j->value = i->value;
  51.                 i->value = tmp;
  52.                
  53.                 swapped = true;
  54.             }
  55.         }
  56.         if (!swapped) {
  57.             return;
  58.         }
  59.     }
  60. }
  61.  
  62. int main()
  63. {
  64.     myQ* que = new myQ();
  65.     que->add(3);
  66.     que->add(6);
  67.     que->add(67);
  68.     que->add(5);
  69.     que->add(222);
  70.     que->add(5);
  71.     que->add(5);
  72.     que->add(6666);
  73.     que->add(2);
  74.     que->add(44);
  75.     que->add(1);
  76.    
  77.     sortQ(que);
  78.    
  79.     cout << "-------" << endl;
  80.     node* it = que->first;
  81.     while(it) {
  82.         cout << it->value << endl;
  83.         it = it->next;
  84.     }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement