forked from Fabayu/HACKTOBERFEST-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuick_sort.cpp
85 lines (66 loc) · 1.49 KB
/
Quick_sort.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
#include <iostream>
#include <algorithm>
using namespace std;
int partition(int *arr, int s, int e)
{
int pivot = arr[s];
int count = 0;
// It will count ki pivot se bade kitne element hai
for (int i = s + 1; i <= e; i++)
{
if (arr[i] <= pivot)
{
count++;
}
}
// place pivot to the right posistion
int pivotIndex = count + s;
swap(arr[pivotIndex], arr[s]);
// left & right wla paer
int i = s;
int j = e;
while (i < pivotIndex && j > pivotIndex)
{
while(arr[i] < pivot)
{
i++;
}
while(arr[j] > pivot)
{
j--;
}
if (i < pivotIndex && j > pivotIndex)
{
swap(arr[i++], arr[j--]) ;
}
}
return pivotIndex;
}
void quick_sort(int *arr, int s, int e)
{
if (s >= e)
return;
int p = partition(arr, s, e);
// for left side .
quick_sort(arr, s, p - 1) ;
// for right side
quick_sort(arr, p + 1, e);
}
int main()
{
int arr[] = {8, 3, 5, 2, 0} ;
int n = sizeof(arr) / sizeof(arr[0]) ;
cout << n << endl;
cout << "Array before quick sort : ";
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
quick_sort(arr, 0, n - 1) ;
cout << endl ;
cout << "Array after quick sort : " ;
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
}