-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.h
More file actions
69 lines (56 loc) · 977 Bytes
/
QuickSort.h
File metadata and controls
69 lines (56 loc) · 977 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
srand((unsigned int) time(nullptr));
int size = 5;
int * A = new int[size];
for (int i = 0; i < size; i++)
{
A[i] = rand() % 100;
}
randomizedQuickSort(A, 0, size - 1);
*/
template <typename T>
int partition(T * A, int p, int r)
{
T x = A[r];
int i = (int)p - 1;
for (int j = p; j < r; j++)
{
if (A[j] <= x)
{
i++;
swap(A[i], A[j]);
}
}
swap(A[i + 1], A[r]);
return i + 1;
}
template <typename T>
void quickSort(T * A, int p, int r)
{
if (p < r)
{
int q = partition(A, p, r);
quickSort(A, p, q - 1);
quickSort(A, q + 1, r);
}
}
int random(int p, int r)
{
return rand() % (r - p + 1) + (p);
}
template <typename T>
int randomizedPartition(T * A, int p, int r)
{
swap(A[r], A[random(p, r)]);
return partition(A, p, r);
}
template <typename T>
void randomizedQuickSort(T * A, int p, int r)
{
if (p < r)
{
int q = randomizedPartition(A, p, r);
randomizedQuickSort(A, p, q - 1);
randomizedQuickSort(A, q + 1, r);
}
}