forked from Adel-Nasim/Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuick Sort.txt
97 lines (81 loc) · 1.37 KB
/
Quick Sort.txt
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
#include<iostream>
using namespace std;
int partition1(int arr[], int l, int h)
{
int p = arr[l];
int i = l;
int j = h;
while (i < j)
{
do
{
i++;
} while (arr[i] <= p);
do
{
j--;
} while (arr[j] > p);
if (i < j)
swap(arr[i], arr[j]);
}
swap(arr[l], arr[j]);
return j;
}
void quickSort1(int arr[], int l, int h)
{
if (l < h) {
int piv = partition1(arr, l, h);
quickSort1(arr, l, piv);
quickSort1(arr, piv + 1, h);
}
}
int partition2(int arr[], int iBegin, int jEnd) {
int i = iBegin;
int j = jEnd;
int pivLoc = i;
while (true)
{
while (arr[pivLoc] <= arr[j] && pivLoc != j)
{
j--;
}
if (pivLoc == j)
break;
else if (arr[pivLoc] > arr[j])
{
swap(arr[j], arr[pivLoc]);
pivLoc = j;
}
while (arr[pivLoc] >= arr[i] && pivLoc != i)
{
i++;
}
if (pivLoc == i)
break;
else if (arr[pivLoc] < arr[i])
{
swap(arr[i], arr[pivLoc]);
pivLoc = i;
}
}
return pivLoc;
}
void quickSort2(int arr[], int l, int h)
{
if (l < h) {
int piv = partition2(arr, l, h);
quickSort2(arr, l, piv - 1);
quickSort2(arr, piv + 1, h);
}
}
int main()
{
int arr[] = { 2,-1,4,7,0 };
int n = sizeof(arr) / sizeof(arr[0]);
quickSort2(arr, 0, n - 1);
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
return 0;
}