forked from ppsirker/dsalgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSortStack.java
48 lines (43 loc) · 850 Bytes
/
SortStack.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
For problem and solution description please visit the link below
http://www.dsalgo.com/2013/02/sort-stack.html
*/
package com.dsalgo;
import java.util.Stack;
public class SortStack
{
public static void main(String[] args)
{
Stack<Integer>stack=new Stack<Integer>();
stack.push(5);
stack.push(3);
stack.push(9);
stack.push(2);
stack.push(6);
sort(stack);
while(!stack.isEmpty())
{
System.out.println(stack.pop());
}
}
static void sort(Stack<Integer> stack)
{
if (stack.isEmpty())
return;
Integer top = stack.pop();
sort(stack);
insertSorted(top, stack);
return;
}
static void insertSorted(Integer top, Stack<Integer> stack)
{
if (stack.isEmpty() || stack.peek() > top)
{
stack.push(top);
return;
}
Integer smaller = stack.pop();
insertSorted(top, stack);
stack.push(smaller);
}
}