Advertisement
apl-mhd

stack sort without loop

Apr 21st, 2017
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.97 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int index =-1;
  5. int number[100];
  6. int size=100;
  7. void push(int x){
  8.    
  9.     if(index+1==size){
  10.         cout<<"overFlow\n";
  11.         }
  12.     else{
  13.     index++;
  14.     number[index] = x;
  15. }
  16.     }
  17.    
  18. int top(){
  19.    
  20.    
  21. return number[index];  
  22.     }
  23.    
  24. void pop(){
  25.    
  26.     if(index<0)
  27.         cout<<"underflow";
  28.     else
  29.     index-=1;
  30.    
  31.     }
  32.    
  33.    
  34.    
  35. void display(){
  36.    
  37.     for(int i=0;i<=index;i++)
  38.         cout<<number[i]<<" ";
  39.         cout<<endl;
  40.    
  41.     }
  42. bool empty(){
  43.    
  44.     if (index ==-1)
  45.         return true;
  46.        
  47.     return false;
  48.    
  49.     }
  50.    
  51. void sortInsert(int x){
  52.    
  53.     if(empty() || x>top()){
  54.        
  55.         push(x);
  56.         return;
  57.        
  58.         }
  59.     int p = top();
  60.     pop();
  61.     sortInsert(x);
  62.     push(p);
  63.    
  64.     }  
  65.    
  66. void sortStack(){
  67.     if( !empty()){
  68.        
  69.         int x = top();
  70.         pop();
  71.         sortStack();
  72.         //cout<<x<<" ";
  73.         sortInsert(x);
  74.         //cout<<x<<" ";
  75.         }
  76.     }
  77.  
  78. int main(int argc, char **argv)
  79. {
  80.  
  81.     push(100);
  82.     push(20);
  83.     push(-10);
  84.     push(1);
  85.     push(2);
  86.    
  87.     sortStack();
  88.     display();
  89.    
  90.    
  91.    
  92.     return 0;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement