-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStackRecursiveSort.java
44 lines (39 loc) · 1.04 KB
/
StackRecursiveSort.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
package datastructure.stack.program;
import datastructure.stack.Stack;
public class StackRecursiveSort {
public static void main(String[] args) throws Exception {
Stack<Integer> stack = new Stack<>();
stack.push(30);
stack.push(-5);
stack.push(18);
stack.push(14);
stack.push(-3);
System.out.println(stack);
sort(stack);
System.out.println(stack);
}
// pop everything recursively and maintain it in the method stack
private static void sort(Stack<Integer> stack) throws Exception {
if (stack.peek() == null)
return;
int temp = stack.pop();
sort(stack);
insert(stack, temp);
}
// push if greater then top else pop everything recursively until smaller
// element is encountered and then push
private static void insert(Stack<Integer> stack, int temp) throws Exception {
if (stack.peek() == null) {
stack.push(temp);
return;
}
if (stack.peek() > temp) {
int i = stack.pop();
insert(stack, temp);
stack.push(i);
} else {
stack.push(temp);
}
return;
}
}