-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.cpp
More file actions
60 lines (48 loc) · 1.22 KB
/
QuickSort.cpp
File metadata and controls
60 lines (48 loc) · 1.22 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
// Basically in quick sort we make some element as pivot and in recursive call we place it at its correct position
// then again try the recusrive calls to its left and right to make rest of the elements at its correct position
#include <bits/stdc++.h>
int pivot1(vector<int>& v, int low, int high)
{
int pivot = v[high];
int j = low - 1;
for (int i = low; i < high; i++)
{
if (v[i] < pivot)
{
j++;
swap(v[i], v[j]);
}
}
swap(v[j + 1], v[high]); // Here dealing with pivot element as at last we stops at position where
//is the actual position of pivot element
return j + 1; // Returning index of pivot element
}
void quick_sort(vector<int>& v, int low, int high)
{
if (low < high) {
int pivot_index = pivot1(v, low, high);
quick_sort(v, low, pivot_index - 1); // not adding pivot element int recursive function
quick_sort(v, pivot_index + 1, high);
}
}
void solve()
{
vector<int>v(6);
v = {1, 2, 2, 5, 3, 2};
int n = v.size();
for (int i = 0; i < v.size(); i++) cout << v[i] << " ";
cout << endl;
quick_sort(v, 0, n - 1);
for (int i = 0; i < v.size(); i++) cout << v[i] << " ";
}
int32_t main()
{
fast;
ll t = 1;
// cin >> t;
while (t--)
{
solve();
}
return 0;
}