forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort-an-array.cpp
53 lines (49 loc) · 1.38 KB
/
sort-an-array.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
// Time: O(nlogn)
// Space: O(n)
// merge sort solution
class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
mergeSort(0, nums.size(), &nums);
return nums;
}
private:
void mergeSort(int start, int end, vector<int> *nums) {
if (end - start <= 1) {
return;
}
const auto& mid = start + (end - start) / 2;
mergeSort(start, mid, nums);
mergeSort(mid, end, nums);
vector<int> tmp;
for (int left = start, right = mid; left < mid; ++left) {
while (right < end && (*nums)[right] < (*nums)[left]) {
tmp.emplace_back((*nums)[right++]);
}
tmp.emplace_back((*nums)[left]);
}
copy(tmp.cbegin(), tmp.cend(), nums->begin() + start);
}
};
// Time: O(nlogn), on average
// Space: O(logn)
// quick sort solution
class Solution2 {
public:
vector<int> sortArray(vector<int>& nums) {
quickSort(0, nums.size(), &nums);
return nums;
}
private:
void quickSort(int start, int end, vector<int> *nums) {
if (end - start <= 1) {
return;
}
const auto& mid = start + (end - start) / 2;
nth_element(nums->begin() + start,
nums->begin() + mid,
nums->begin() + end);
quickSort(start, mid, nums);
quickSort(mid, end, nums);
}
};