Web Toolbar by Wibiya

Pages

Monday, April 25, 2011

Sort a stack in ascending order when standard stack operations(push, pop, peek and isEmpty) are given.

Solution #1: We can use another stack to do the sorting. Suppose s1 is the original stack and s2 is the other stack. The algorithm will look like this,

- Pop from s1(e1) and peek s2(e2).
- if e2 < e1, then push e1 on s2,
- if e2 > e1, then keep popping from s2 into s1 till the next element is less than e1 and then push e1 on s2.

Keep doing it till s1 is empty. Now, s2 will be sorted in ascending order! This algorithm will have a time complexity of O(N^2).

2 comments:

$\-\(=LLy said...

What does peek() mean??

Suchit Maindola said...

peek() or top() operation tell you the top most element of the stack without popping it.