Advertisement
jcvitanovic

Zad18

Dec 26th, 2014
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. /*
  2. 26.12.2014
  3. Probl em 18 Given a stack S, write a C program to sort the stack (in ascending order).
  4. You are not allowed to make any assumptions about how the stack is implemented; the only
  5. functions allowed to be used are: Push, Pop, Top, IsEmpty, IsFull
  6. */
  7.  
  8. #include<stdio.h>
  9. #include<iostream>
  10. #include<vector>
  11. #include<stdlib.h>
  12. #include<time.h>
  13.  
  14. using namespace std;
  15.  
  16. class Stack {
  17.  
  18. private:
  19.     int size = 0;
  20.     vector<int> items;
  21. public:
  22.  
  23.     Stack(){
  24.         items = vector<int>(1);
  25.     }
  26.  
  27.     bool IsEmpty(){
  28.         return size == 0;
  29.     }
  30.     int Pop(){
  31.         int popItem = items[size - 1];
  32.         size--;
  33.         if ((size > 0) && (size == items.size() / 4)){
  34.             items.resize(items.size() / 2);
  35.         }
  36.         return popItem;
  37.     }
  38.     void Push(int item){
  39.         size++;
  40.         items[size - 1] = item;
  41.         if (size == items.size()){
  42.             items.resize(items.size() * 2);
  43.         }
  44.     }
  45.     int Top(){
  46.         return items[size - 1];
  47.     }
  48. };
  49.  
  50. void pushValueInPlace(Stack &stack, int value){
  51.     if (stack.IsEmpty())
  52.         stack.Push(value);
  53.     else{
  54.         if (stack.Top() < value){
  55.             int mem = stack.Pop();
  56.             pushValueInPlace(stack, value);
  57.             stack.Push(mem);
  58.         }
  59.         else
  60.             stack.Push(value);
  61.     }
  62. }
  63.  
  64. void sortStack(Stack &stack){
  65.     if (stack.IsEmpty())
  66.         return;
  67.     int top = stack.Pop();
  68.     sortStack(stack);
  69.     pushValueInPlace(stack, top);
  70.  
  71. }
  72.  
  73. int main(){
  74.     Stack stack;
  75.  
  76.     srand(time(NULL));
  77.  
  78.  
  79.     for (int i = 0; i < 15; i++){
  80.         int num = rand() % 100 + 1;
  81.         stack.Push(num);
  82.     }
  83.  
  84.     sortStack(stack);
  85.  
  86.     while (!stack.IsEmpty()){
  87.         cout << stack.Pop() << " ";
  88.     }
  89.     cout << "\n";
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement