forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QuickSort.cpp
65 lines (56 loc) · 1.17 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
#include <iostream>
#include <vector>
using namespace std;
int partition(vector<int> &vector, int start, int end)
{
int pivot = vector[end];
int index = start;
for (int i = start; i < end; i++)
{
if (vector[i] < pivot)
{
int temp = vector[i];
vector[i] = vector[index];
vector[index] = temp;
index++;
}
}
if (pivot <= vector[index])
{
vector[end] = vector[index];
vector[index] = pivot;
}
return index;
}
void quickSort(vector<int> &vector, int start, int end)
{
if (start < end)
{
int pivot = partition(vector, start, end);
quickSort(vector, start, pivot-1);
quickSort(vector, pivot+1, end);
}
}
void quickSort(vector<int> &vector)
{
quickSort(vector, 0, vector.size()-1);
}
void showVector(vector<int> vector)
{
for (uint32_t i = 0; i < vector.size(); ++i)
{
cout << vector[i] << ", ";
}
cout << "\n";
}
int main()
{
vector<int> vector;
for (uint32_t i = 0; i < 10; ++i)
{
vector.push_back(rand() % 100);
}
showVector(vector);
quickSort(vector);
showVector(vector);
}