-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathquick-sort.cpp
More file actions
37 lines (34 loc) · 805 Bytes
/
quick-sort.cpp
File metadata and controls
37 lines (34 loc) · 805 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
#include <vector>
using namespace std;
void swap(int i, int j, vector<int>& array) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
void quickSortHelper(vector<int>& array, int start, int end) {
if (start >= end) return;
int left = start + 1;
int right = end;
int pivot = array[start];
while (right >= left) {
int leftVal = array[left];
int rightVal = array[right];
if (leftVal > pivot && rightVal < pivot) {
swap(left, right, array);
}
if (leftVal <= pivot) {
left++;
}
if (rightVal >= pivot) {
right--;
}
}
swap(start, right, array);
quickSortHelper(array, start, right - 1);
quickSortHelper(array, right + 1, end);
}
vector<int> quickSort(vector<int> array) {
// Write your code here.
quickSortHelper(array, 0, array.size() - 1);
return array;
}