-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsorting_an_stack_(inplace_sorting).java
65 lines (55 loc) · 1.28 KB
/
sorting_an_stack_(inplace_sorting).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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
https://www.geeksforgeeks.org/sort-a-stack-using-recursion/
*/
/**
*
* @author shivam
*/
//Time complexity O(n^2).. but space complexity is O(1)(thats efficient) :p
import java.util.Stack;
public class sort_a_stack__using_recursion_inplace_sorting {
static Stack<Integer> s= new Stack<Integer>();
static void sorted_insert(int a)
{
if(s.isEmpty() || a>s.peek())
{
s.push(a);
return;
}
int temp=s.peek();
s.pop();
sorted_insert(a);
s.push(temp);
}
static void sort()
{
if(s.isEmpty()!=true)
{
int a=s.peek();
s.pop();
sort();
sorted_insert(a);
}
}
//driver
public static void main(String[] args) {
s.push(30);
s.push(-5);
s.push(18);
s.push(14);
s.push(-3);
System.out.println("before sorting stack is as follows");
System.out.println(s);
sort();
System.out.println("before sorting stack is as follows");
System.out.println(s);
}
}
/*
run:
original stack is as follows
[1, 2, 3, 4]
After reverse sort, stack is as follows
[4, 3, 2, 1]
BUILD SUCCESSFUL (total time: 0 seconds)
*/