Skip to content

Commit ac41bf4

Browse files
authored
Create SortAnArray.cpp
1 parent 5b197f6 commit ac41bf4

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

medium/SortAnArray.cpp

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
//912. Sort an Array
2+
class Solution {
3+
public:
4+
vector<int> sortArray(vector<int>& nums) {
5+
mergeSort(nums, 0, nums.size() - 1);
6+
return nums;
7+
}
8+
9+
private:
10+
void mergeSort(vector<int>& A, int l, int r) {
11+
if (l >= r)
12+
return;
13+
14+
const int m = (l + r) / 2;
15+
mergeSort(A, l, m);
16+
mergeSort(A, m + 1, r);
17+
merge(A, l, m, r);
18+
}
19+
20+
void merge(vector<int>& A, int l, int m, int r) {
21+
vector<int> sorted(r - l + 1);
22+
int k = 0; // sorted's index
23+
int i = l; // left's index
24+
int j = m + 1; // right's index
25+
26+
while (i <= m && j <= r)
27+
if (A[i] < A[j])
28+
sorted[k++] = A[i++];
29+
else
30+
sorted[k++] = A[j++];
31+
32+
// Put possible remaining left part to the sorted array
33+
while (i <= m)
34+
sorted[k++] = A[i++];
35+
36+
// Put possible remaining right part to the sorted array
37+
while (j <= r)
38+
sorted[k++] = A[j++];
39+
40+
copy(begin(sorted), end(sorted), begin(A) + l);
41+
}
42+
};

0 commit comments

Comments
 (0)