Skip to content

Commit 1ef0a55

Browse files
committed
Add QuickSort
1 parent 9d688f2 commit 1ef0a55

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

QuickSort.cpp

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
class QuickSort {
6+
private:
7+
vector<int> nums;
8+
9+
int partition(int left, int right) {
10+
int mid = left + ((right - left) >> 1);
11+
int pivot = nums[mid];
12+
int i = left - 1;
13+
14+
for (int j = left; j < right; j++) {
15+
if (nums[j] < pivot)
16+
swap(nums[++i], nums[j]);
17+
}
18+
19+
swap(nums[i + 1], nums[right]);
20+
return i + 1;
21+
}
22+
23+
void quickSort(int left, int right) {
24+
if (left >= right)
25+
return;
26+
27+
int pivot = partition(left, right);
28+
29+
quickSort(left, pivot - 1);
30+
quickSort(pivot + 1, right);
31+
}
32+
33+
public:
34+
QuickSort(const vector<int> &nums) : nums(nums) {}
35+
36+
void sort() { quickSort(0, nums.size() - 1); }
37+
38+
vector<int> getSortedArray() { return nums; }
39+
};

0 commit comments

Comments
 (0)