归并排序非递归C++代码
时间: 2024-06-23 07:00:35 浏览: 202
归并排序的c++代码
5星 · 资源好评率100%
归并排序是一种经典的分治算法,非递归实现通常使用栈来模拟递归过程。以下是一个简单的归并排序非递归版本的C++代码:
```cpp
#include <iostream>
#include <vector>
#include <stack>
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 mergeSortNonRecursive(std::vector<int>& arr, int left, int right) {
if (left < right) {
// 计算中间索引
int mid = left + (right - left) / 2;
// 递归地对左半部分和右半部分进行排序
mergeSortNonRecursive(arr, left, mid);
mergeSortNonRecursive(arr, mid + 1, right);
// 合并左右两个有序部分
merge(arr, left, mid, right);
}
}
int main() {
std::vector<int> arr = {9, 7, 5, 11, 12, 2, 14, 3, 10, 6};
int n = arr.size();
std::cout << "Original array: ";
for (int i : arr)
std::cout << i << " ";
std::cout << "\n";
mergeSortNonRecursive(arr, 0, n - 1);
std::cout << "Sorted array: ";
for (int i : arr)
std::cout << i << " ";
std::cout << "\n";
return 0;
}
```
阅读全文