-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsort_an_array.cpp
45 lines (41 loc) · 1.15 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
class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
return mergeSort(nums, 0, nums.size()-1);
}
vector<int> merge(vector<int>& a, vector<int>& b) {
vector<int> result;
int i = 0; int j = 0; // Index of subarrays
while (i < a.size() && j < b.size()) {
if (a[i] < b[j]) {
result.push_back(a[i]);
i++;
} else {
result.push_back(b[j]);
j++;
}
}
// Fill with rest of A
while (i < a.size()) {
result.push_back(a[i]);
i++;
}
// Fill with rest of B
while (j < b.size()) {
result.push_back(b[j]);
j++;
}
return result;
}
vector<int> mergeSort(vector<int>& nums, int start, int end) {
// Base case
if (end - start <= 0) {
return { nums[start] };
}
// Recursive
int mid = (start + end) / 2;
vector<int> a = mergeSort(nums, start, mid);
vector<int> b = mergeSort(nums, mid+1, end);
return merge(a,b);
}
};