-
Notifications
You must be signed in to change notification settings - Fork 43
/
QuickSortUsingStack.cpp
60 lines (53 loc) · 1.08 KB
/
QuickSortUsingStack.cpp
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
#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int pi = low;
for (int i = low; i < high; i++)
{
if (arr[i] <= pivot)
{
swap(arr[i], arr[pi]);
pi++;
}
}
swap (arr[pi], arr[high]);
return pi;
}
void iterativeQuicksort(int arr[], int n)
{
stack<pair<int, int>> st;
int low = 0;
int high = n - 1;
st.push(make_pair(low, high));
while (!st.empty())
{
low = st.top().first, high = st.top().second;
st.pop();
int pivot = partition(arr, low, high);
if (pivot - 1 > low) {
st.push(make_pair(low, pivot - 1));
}
if (pivot + 1 < high) {
st.push(make_pair(pivot + 1, high));
}
}
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++){
cin>>arr[i];
}
iterativeQuicksort(arr, n);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}