-
Notifications
You must be signed in to change notification settings - Fork 1
/
QuickSort.cpp
116 lines (91 loc) · 2.33 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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/**
*
* Title: Quick Sort
* Description: Perform Quick Sort algorithm on a given list of numbers.
* Author: Ajit Panigrahi
* GitHub: https://github.com/AjitZero
* Twitter: https://twitter.com/AjitZero
*
*/
#include <iostream>
#include <vector>
using namespace std;
/**
* Utility function for Swapping two numbers
*
* @param first [First number]
* @param second [Second number]
*/
void swap(int &first, int &second) {
int temp = first;
first = second;
second = temp;
}
/**
* Partitions the list in the given range with a selected element as pivot and places all elements smaller than the pivot to its left and the rest to the right of pivot
*
* @param v [List of values]
* @param low [Lower bound limit]
* @param high [Upper bound limit]
* @return [Finalised sorted position]
*/
int partition (vector<int>& v, int low, int high) {
// Choosing pivot as last element
int pivot = v[high];
// Index of smaller element
int i = low - 1;
// Check all elements in range with pivot
for (int j = low; j <= high - 1; ++j) {
// If current element is smaller than or equal to pivot
if (v[j] <= pivot) {
// Increment lower value to switch with pivot
++i;
// Switch with lower element
swap(v[i], v[j]);
}
}
// Switch with pivot
swap(v[i + 1], v[high]);
// Return the fixed pivot position
return i + 1;
}
/**
* Driver function for Quick Sort
*
* @param v [List of values]
* @param low [Lower bound limit]
* @param high [Upper bound limit]
*/
void quickSort(vector<int>& v, int low, int high) {
// Only for valid ranges
if (low < high) {
// v[sortedPosition] is at the right position on partitioning
int sortedPosition = partition(v, low, high);
// Separate sorting of sub-list before partition and after partition
quickSort(v, low, sortedPosition - 1);
quickSort(v, sortedPosition + 1, high);
}
}
// Driver function
int main() {
int noOfElements;
cin >> noOfElements;
vector<int> V(noOfElements);
// Enter `noOfElements` values:
for (int i = 0; i < noOfElements; ++i)
cin >> V[i];
quickSort(V, 0, noOfElements - 1);
// Sorted values:
for (int i = 0; i < noOfElements; ++i)
cout << V[i] << ' ';
return 0;
}
/*
Sample Input:
--------------------
15
3 44 38 5 47 15 36 26 27 2 46 4 19 50 48
Sample Output:
--------------------
2 3 4 5 15 19 26 27 36 38 44 46 47 48 50
*/