-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathBubbleSortStack.java
More file actions
85 lines (68 loc) · 2.34 KB
/
BubbleSortStack.java
File metadata and controls
85 lines (68 loc) · 2.34 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
83
84
85
import java.util.*;
public class BubbleSortStack
{
static void bubbleSortStack(int arr[], int n)
{
Stack<Integer> s1 = new Stack<>();
for (int num : arr)
s1.push(num);
Stack<Integer> s2 = new Stack<>();
for (int i = 0; i < n; i++)
{
if (i % 2 == 0)
{
while (!s1.isEmpty())
{
int t = s1.pop();
if (s2.isEmpty())
s2.push(t);
else
{
if (s2.peek() > t)
{
// swapping
int temp = s2.pop();
s2.push(t);
s2.push(temp);
}
else
{
s2.push(t);
}
}
}
arr[n-1-i] = s2.pop();
}
else
{
while(!s2.isEmpty())
{
int t = s2.pop();
if (s1.isEmpty())
s1.push(t);
else
{
if (s1.peek() > t)
{
int temp = s1.pop();
s1.push(t);
s1.push(temp);
}
else
s1.push(t);
}
}
arr[n-1-i] = s1.pop();
}
}
System.out.println(Arrays.toString(arr));
}
public static void main(String[] args)
{ Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
bubbleSortStack(arr, n);
}
}