-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathP15.java
More file actions
82 lines (60 loc) · 2.01 KB
/
P15.java
File metadata and controls
82 lines (60 loc) · 2.01 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package stack_and_queue;
import java.util.Stack;
import java.util.*;
// Program Title => Sort a stack using Recursion
public class P15 {
// Recursive Method to insert an item x in sorted way
static void sortedInsert(Stack<Integer> s, int x){
// Base case: Either stack is empty or newly inserted item is greater than top (more than all existing)
if(s.isEmpty() || x > s.peek()){
s.push(x);
return;
}
// if top is greater, remove the top item and recur
int temp = s.pop();
sortedInsert(s, x);
// put back the top item removed earlier
s.push(temp);
}
// function to sort the stack
static void sortStack(Stack<Integer> s){
// checking if stack is not empty
if(!s.isEmpty()){
// Remove the top item
int x = s.pop();
// Sort remainig stack
sortStack(s);
// Push the top item back in sorted stack
sortedInsert(s,x);
}
}
// function to sort the arrays.array
static void printStack(Stack<Integer> s){
ListIterator<Integer> lt = s.listIterator();
// forwarding
while(lt.hasNext())
lt.next();
// printing from top to bottom
while (lt.hasPrevious())
System.out.println(lt.previous() + " ");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] array = new int[n];
Stack<Integer> s = new Stack<>();
for(int i= 0; i < array.length; i++){
System.out.println("Enter your number: ");
int value = sc.nextInt();
s.push(value);
}
sc.close();
while (!(s.isEmpty()))
System.out.println(s.pop());
System.out.println("Stack elements before sorting: ");
printStack(s);
sortStack(s);
System.out.println(" \n\nStack elements after sorting:");
printStack(s);
}
}