### Thread: Function to Sort Stack - high to low with 2 temp stack

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2012
Posts
9
Rep Power
0

#### Function to Sort Stack - high to low with 2 temp stack

we get queshtion that we need to :
sort stack with high to low sorted,
with no Array!!!
some suggest me to write program with 2 stack ,
1- to sorted
2- for temp stack to help me sorted numbers to stack 1

2. No Profile Picture
bdb
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Aug 2012
Posts
156
Rep Power
34
Lets name the temporary stacks as A and B. They are initially empty, of course.

1) examine the first element of the original stack: let's call it F; if empty go to 6
2) while the top element of A is bigger than F move it to B
3) move F to A (pop from original stack, push to A)
4) move all elements in B to A (pop from B, push to A)
5) go to 1
6) move all elements of A to the original stack
Voila!

Of course you can change the comparison to order the other way around ... and save on stack transfers with some clever tests.
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2012
Posts
9
Rep Power
0

#### thank u

first of all , thank u that u reply me an anser,
i now the algoritem on my paper but how can i write the function to do it ?!

4. No Profile Picture
bdb
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Aug 2012
Posts
156
Rep Power
34
Originally Posted by tsahar
...how can i write the function to do it ?!
No "copy/paste" programming here.

1) Write the function.
2) Publish it here with a comment about what does not work, the input, expected output and actual output ...
3) Wait for comments from fellow programmers.
4) Inprove your code with the presented suggestion.
5) if still not happy, go back to step 2
6) Finished
5. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2012
Posts
9
Rep Power
0

#### function to - sort stack with 2 temp stack, no array!!!

# include<stdio.h>

02 # include<string.h>

03 # include<conio.h>

04 # include <stdlib.h>

05 # define N 10

06

07 void my_sort(stackint a, int head)

08 {

09 int /*a[N],*/ sorted[N] , help[N];

14 push(sorted,pop(a));

15 while (!is_empty(a))

16 {

17 num = pop(a);

18 nums = top(sorted);

19 if (num>= nums) push(sorted,num);

20 else

21 {

22 while (num< nums)

23 {

24 push(help,pop(sorted));

25 nums = top(sorted);

26 } // while

27 push(sorted,num);

28 while(!is_empty(help))

29 {

30 push(sorted,pop(help));

31 }//while

32 }//else

33 }//while

34 //getch = ch;

35 }//func
6. No Profile Picture
bdb
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Aug 2012
Posts
156
Rep Power
34
What's stackint?
You're creating arrays at line 9

Also, use code tags when posting code ... and lose the line numbers.