-
Notifications
You must be signed in to change notification settings - Fork 256
/
03 Merge sort.cpp
50 lines (40 loc) · 930 Bytes
/
03 Merge sort.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
class Solution {
public:
void merge(vector<int>& nums, int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int A[n1], B[n2];
for(int i = 0; i < n1; i++)
A[i] = nums[l + i];
for(int i = 0; i < n2; i++)
B[i] = nums[m + 1 + i];
int i = 0, j = 0;
int k = l;
while(i < n1 && j < n2)
{
if(A[i] <= B[j])
nums[k++] = A[i++];
else
nums[k++] = B[j++];
}
while(i < n1)
nums[k++] = A[i++];
while(j < n2)
nums[k++] = B[j++];
}
void mergeSort(vector<int>& nums, int l, int r)
{
if(l >= r) //remember to put the equal to sign
return;
int m = l + (r - l)/2;
mergeSort(nums, l, m);
mergeSort(nums, m + 1, r);
merge(nums, l, m, r);
}
vector<int> sortArray(vector<int>& nums)
{
mergeSort(nums, 0, nums.size() - 1);
return nums;
}
};