forked from Nikhil-2002/Programming_Hactoberfest23
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quickSort.cpp
75 lines (60 loc) · 1.2 KB
/
quickSort.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
#include <iostream>
using namespace std;
int partion(int *arr, int s, int e)
{
// Take pivot
int p = arr[s];
int cnt = 0;
// find right posn of pivot
for (int i = s + 1; i <= e; i++)
{
if (arr[i] <= p)
cnt++;
}
// place pivot at right position
int pIndex = s + cnt;
swap(arr[pIndex], arr[s]);
// Now, partion kro
int i = s;
int j = e;
while (i < pIndex && j > pIndex)
{
while (arr[i] < p) // left part
{
i++;
}
while (arr[j] > p)
{
j--;
}
if (i < pIndex && j > pIndex)
{
swap(arr[i++], arr[j--]);
}
}
return pIndex;
}
void quickSort(int *arr, int s, int e)
{
// base case
if (s >= e)
return;
// partition
int pivot = partion(arr, s, e);
// left part sort
quickSort(arr, s, pivot - 1);
// right part sort
quickSort(arr, pivot + 1, e);
}
int main()
{
int arr[] = {3, 1, 4, 5, 2};
int n = sizeof(arr) / sizeof(int);
quickSort(arr, 0, n - 1);
cout << "Quick Sorting" << endl;
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
return 0;
}