自底向上合并排序算法C++代码
时间: 2024-09-25 13:02:37 浏览: 26
自底向上的归并排序是一种分治策略,它将数组不断划分为越来越小的子数组,直到每个子数组只有一个元素,然后逐步合并这些子数组回到原数组,直到整个数组有序。以下是C++实现自底向上合并排序的一个简单版本:
```cpp
#include <vector>
void merge(std::vector<int>& arr, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
std::vector<int> L(n1), R(n2);
for (int i = 0; i < n1; ++i)
L[i] = arr[left + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[mid + 1 + j];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
// 将剩余未比较的元素复制回数组
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(std::vector<int>& arr, int left = 0, int right = -1) {
if (right == -1) {
right = arr.size() - 1;
}
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
阅读全文