[AlgoExpert] Merge Sort

Merge Sort

  • Time : O(nlogn)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void dnc(vector<int>& A, int l, int r) {
if(l == r) return;
int m = (l + r) / 2;
dnc(A, l, m);
dnc(A, m + 1, r);

vector<int> sorted;
int i = l, j = m + 1;
while(i <= m and j <= r) {
if(A[i] < A[j]) sorted.push_back(A[i++]);
else sorted.push_back(A[j++]);
}
while(i <= m) sorted.push_back(A[i++]);
while(j <= r) sorted.push_back(A[j++]);
for(auto& s : sorted) A[l++] = s;
}

vector<int> mergeSort(vector<int> array) {
dnc(array, 0, array.size() - 1);
return array;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/merge-sort/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.