Skip to content

Commit 442e00a

Browse files
authored
Bubble sort using two Stacks
1 parent 99cf7d7 commit 442e00a

1 file changed

Lines changed: 90 additions & 0 deletions

File tree

‎Bubble sort using two Stacks‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
// Java program for bubble sort
2+
// using stack
3+
4+
import java.util.Arrays;
5+
import java.util.Stack;
6+
7+
public class Test
8+
{
9+
// Method for bubble sort using Stack
10+
static void bubbleSortStack(int arr[], int n)
11+
{
12+
Stack<Integer> s1 = new Stack<>();
13+
14+
// Push all elements of array in 1st stack
15+
for (int num : arr)
16+
s1.push(num);
17+
18+
Stack<Integer> s2 = new Stack<>();
19+
20+
for (int i = 0; i < n; i++)
21+
{
22+
// alternatively
23+
if (i % 2 == 0)
24+
{
25+
while (!s1.isEmpty())
26+
{
27+
int t = s1.pop();
28+
29+
if (s2.isEmpty())
30+
s2.push(t);
31+
else
32+
{
33+
if (s2.peek() > t)
34+
{
35+
// swapping
36+
int temp = s2.pop();
37+
s2.push(t);
38+
s2.push(temp);
39+
}
40+
else
41+
{
42+
s2.push(t);
43+
}
44+
}
45+
}
46+
47+
// tricky step
48+
arr[n-1-i] = s2.pop();
49+
}
50+
else
51+
{
52+
while(!s2.isEmpty())
53+
{
54+
int t = s2.pop();
55+
56+
if (s1.isEmpty())
57+
s1.push(t);
58+
59+
else
60+
{
61+
if (s1.peek() > t)
62+
{
63+
// swapping
64+
int temp = s1.pop();
65+
66+
s1.push(t);
67+
s1.push(temp);
68+
}
69+
else
70+
s1.push(t);
71+
}
72+
}
73+
74+
// tricky step
75+
arr[n-1-i] = s1.pop();
76+
}
77+
}
78+
System.out.println(Arrays.toString(arr));
79+
}
80+
81+
// Driver Method
82+
public static void main(String[] args)
83+
{
84+
int arr[] = {15, 12, 44, 2, 5, 10};
85+
bubbleSortStack(arr, arr.length);
86+
}
87+
}
88+
89+
90+
//output :- [2, 5, 10, 12, 15, 44]

0 commit comments

Comments
 (0)