-
Notifications
You must be signed in to change notification settings - Fork 0
/
15_Iterative_QS.cpp
97 lines (94 loc) · 2.62 KB
/
15_Iterative_QS.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
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
86
87
88
89
90
91
92
93
94
95
96
97
// Iterative Quick Sort + Analysis of it's Space Complexity by keeping the track of recursion calls made
#include <bits/stdc++.h>
using namespace std;
using namespace std ::chrono;
int partition(vector<int> &arr, int low, int high)
{
int i = low;
int j = high;
int pivot = arr[low];
while (i < j)
{
while (arr[i] <= pivot && i <= high - 1)
i++;
while (arr[j] > pivot && j >= low + 1)
j--;
if (i < j)
swap(arr[i], arr[j]);
}
swap(arr[low], arr[j]);
return j;
}
void IterativeQS(vector<int> &arr, int low, int high, int &recCalls)
{
// low and high of the separated portion of elements
stack<pair<int, int>> st;
while (1)
{
while (low < high)
{
int j = partition(arr, low, high);
if (j - low > high - j)
{
st.push({low, j - 1});
low = j + 1;
recCalls++;
}
else
{
st.push({j + 1, high});
high = j - 1;
recCalls++;
}
// cout << endl << "Recursion Calls made are :- " << recCalls << endl ;
}
if (st.empty())
{
recCalls--;
return;
}
low = st.top().first;
high = st.top().second;
st.pop();
}
}
void input_generator(vector<pair<int, pair<int, int>>> &store)
{
for (int i = 1e3; i <= 1500; i += 50)
{
vector<int> arr(i);
for (int it = 0; it < i; it++)
{
arr[it] = rand() % 50;
}
clock_t time_req;
int t = 0;
int recCalls = 0;
int avgCalls = 0;
for (int m = 1; m <= 10; m++)
{
auto start = high_resolution_clock::now();
recCalls = 0;
IterativeQS(arr, 0, i - 1, recCalls);
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
t += duration.count();
avgCalls += recCalls;
}
t = t / 10;
avgCalls /= 10;
store.push_back({i, {t, avgCalls}});
}
}
int main()
{
// Inputs,Time taken and average recursion calls made each time for n number of elements
vector<pair<int, pair<int, int>>> store;
input_generator(store);
cout << "Number of inputs \tTime taken \tRecursive Calls\n\n";
for (auto i : store)
{
cout << i.first << " \t" << i.second.first << "\t\t" << i.second.second << endl;
}
return 0;
}