-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubbleSortUsing2Stacks.cpp
More file actions
62 lines (53 loc) · 1.15 KB
/
bubbleSortUsing2Stacks.cpp
File metadata and controls
62 lines (53 loc) · 1.15 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
#include<iostream>
#include<stack>
using namespace std;
int main()
{
stack <int> s1,t;
int n;
cout<<"Enter size of stack ";
cin>>n;
int num;
while(n--) // reading the array
{
cin>>num;
s1.push(num);
}
int temp;
stack <int> s2;
int arr[n];
for(int i=0;i<n;i++)
{
while(!s1.empty())
{
temp=s1.top();
s1.pop();
if(s2.empty())
s2.push(temp);
else
{
if(s2.top()<temp)
s2.push(temp);
else
{
s1.push(s2.top());
s2.pop();
s2.push(temp);
}
}
}
//trick part - storing largest element in stack to the array
arr[n-1-i]=s2.top();
s2.pop();
while(!s2.empty()) // placing all elements to stack s1
{
s1.push(s2.top());
s2.pop();
}
}
// Printing the result sorted array
cout<<"\n";
for(int i=0;i<n;i++)
cout<<arr[i]<<"\t";
return 0;
}