Merge Sort is an algorithm that sorts an array of numbers in non-decreasing order in time and space.
Tip
This problem can also be solved by Selection Sort in time and space.
Tip
This problem can also be solved by Insertion Sort in time and space.
Tip
This problem can also be solved by Bubble Sort in time and space.
Tip
This problem can also be solved by Heapsort in time and space.
Tip
This problem can also be solved by Quicksort in time and space.
Tip
This problem can also be solved by Quickselect in time and space.
Algorithm
-
Let . Sort and recursively.
-
Sort in the following way:
Consider finding the result of sorting , where and .
- If , the minimum element among must be . Find the result of sorting recursively. Let , the result be , then is the result of sorting .
- Otherwise, the minimum element among must be . Find the result of sorting recursively. Let , the result be , then is the result of sorting .
This algorithm solves the problem in time and space.
void merge_sort(int n, std::vector<int> &a) {
std::vector<int> tmp(n);
y_combinator([&](auto &&self, std::vector<int>::iterator l, std::vector<int>::iterator r) -> void {
if (l + 1 == r) {
return;
}
auto mid = l + (r - l) / 2;
self(l, mid), self(mid, r);
auto i = l, j = mid, k = tmp.begin();
while (i != mid && j != r) {
*k++ = *i < *j ? *i++ : *j++;
}
for (; i != mid; i++) {
*k++ = *i;
}
for (; j != r; j++) {
*k++ = *j;
}
std::copy(tmp.begin(), k, l);
})(a.begin(), a.end());
}