-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortStack.java
More file actions
53 lines (52 loc) · 1.65 KB
/
Copy pathSortStack.java
File metadata and controls
53 lines (52 loc) · 1.65 KB
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
49
50
51
52
53
package RecursionAndBacktracking;
import java.util.Scanner;
import java.util.Stack;
/*
* Given a stack we have to sort the stack into ascending order using recursion.
*/
public class SortStack {
private static void sortStack(Stack<Integer> stack){
if(stack.size() == 1)
return;
int temp = stack.pop();
sortStack(stack);
insertTemp(stack, temp);
}
// for Ascending order sorting
public static void insertTemp(Stack<Integer> stack, int temp){
if(stack.size() == 0 || stack.peek() <= temp){
stack.push(temp);
return;
}
int val = stack.pop();
insertTemp(stack, temp);
stack.push(val);
}
// for descending order sorting
// public static void insertTemp(Stack<Integer> stack, int temp){
// if(stack.size() == 0 || stack.peek() >= temp){
// stack.push(temp);
// return;
// }
// int val = stack.pop();
// insertTemp(stack, temp);
// stack.push(val);
// }
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of test cases:");
int t = sc.nextInt();
while (t-- > 0) {
System.out.println("Enter elements: if want to stop enter -1");
Stack<Integer> stack = new Stack<>();
int ele = 0;
ele = sc.nextInt();
while (ele != -1){
stack.push(ele);
ele = sc.nextInt();
}
sortStack(stack);
System.out.println(stack);
}
}
}