[Geeks for Geeks] Merge Sort

Merge Sort

Given an array arr[], its starting position l and its ending position r. Sort the array using merge sort algorithm.

  • 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
23
24
class Solution {
public:
void merge(int arr[], int l, int m, int r) {
int left = l, right = m + 1;
vector<int> sorted;
while(left <= m and right <= r) {
if(arr[left] < arr[right]) sorted.push_back(arr[left++]);
else sorted.push_back(arr[right++]);
}
while(left <= m) sorted.push_back(arr[left++]);
while(right <= r) sorted.push_back(arr[right++]);
for(int i = l; i <= r; i++)
arr[i] = sorted[i - l];
}

public:
void mergeSort(int arr[], int l, int r) {
if(l == r) return;
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/merge-sort/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.