-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSortAlgorithm.cpp
More file actions
48 lines (38 loc) · 868 Bytes
/
QuickSortAlgorithm.cpp
File metadata and controls
48 lines (38 loc) · 868 Bytes
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
#include <iostream>
#include <vector>
using namespace std;
int partition(vector<int> &arr, int st, int end)
{
int idx = st - 1, pivot = arr[end];
for (int j = st; j < end; j++)
{
if (arr[j] <= pivot)
{
idx++;
swap(arr[j], arr[idx]); // left partition
}
}
idx++;
swap(arr[end], arr[idx]); // assigning pivot the right index
return idx;
}
void quickSort(vector<int> &arr, int st, int end)
{
if (st < end)
{
int pivIdx = partition(arr, st, end);
quickSort(arr, st, pivIdx - 1); // left half call
quickSort(arr, pivIdx + 1, end); // right half call
}
}
int main()
{
vector<int> arr = {12, 31, 35, 8, 32, 17};
quickSort(arr, 0, arr.size() - 1);
for (int val : arr)
{
cout << val << " ";
}
cout << endl;
return 0;
}