ashpatel

sorting a stack

Nov 12th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.57 KB | None | 0 0
  1. //Sorting a stack
  2. stack S = [226, 280, 462, 233, 254, 294, 93, 256, 315, 396];/* S is a stack implemented using array with last element in array as top of the stack. In this case top of the stack S is S[9] = 396 */
  3. sortStack(){
  4. if stack is not empty{
  5. int temp = S.pop();
  6. sortStack();
  7. sortedInsert(temp);
  8. }
  9. }
  10.  
  11. sortedInsert(element){
  12. if stack is empty OR element > top element{
  13. S.push(element)
  14. }
  15. else{
  16. int temp = S.pop()
  17. sortedInsert(element)
  18. S.push(temp)
  19. }
  20. }
  21.  
  22. main(){
  23. sortStack();
  24. // S will be sorted when control comes over here..
  25. }
Add Comment
Please, Sign In to add comment