This repository was archived by the owner on Nov 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.cpp
More file actions
68 lines (54 loc) · 1.44 KB
/
Copy pathQuickSort.cpp
File metadata and controls
68 lines (54 loc) · 1.44 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
59
60
61
62
63
64
65
66
67
68
#include "stdafx.h"
#include "QuickSort.h"
#include <algorithm>
#include <set>
QuickSort::QuickSort()
{
}
QuickSort::~QuickSort()
{
}
void QuickSort::sort(int arr[], int size)
{
auto start = 0;
auto end = size -1;
quickSort(arr, start, end);
}
int QuickSort::partition(int arr[], int start, int end)
{
// The pivot element is taken to be the element at
// the start of the subrange to be partitioned
auto pivotValue = arr[start];
auto pivotPosition = start;
// Rearrange the rest of the array elements to
// partition the subrange from start to end
for (auto pos = start + 1; pos <= end; pos++)
{
if (arr[pos] < pivotValue)
{
// arr[scan] is the "current" item.
// Swap the current item with the item to the
// right of the pivot element
std::swap(arr[pivotPosition + 1], arr[pos]);
// Swap the current item with the pivot element
std::swap(arr[pivotPosition], arr[pivotPosition + 1]);
// Adjust the pivot position so it stays with the
// pivot element
pivotPosition++;
}
}
return pivotPosition;
}
void QuickSort::quickSort(int arr[], int start, int end)
{
Comparisons++;
if (start < end)
{
// Partition the array and get the pivot point
auto p = partition(arr, start, end);
// Sort the portion before the pivot point
quickSort(arr, start, p - 1);
// Sort the portion after the pivot point
quickSort(arr, p + 1, end);
}
}