c++二路归并排序迭代法代码
时间: 2023-10-12 14:12:57 浏览: 93
快速排序、堆排序、归并排序、希尔排序实现
以下是C++实现的二路归并排序迭代法代码:
```c++
#include <iostream>
using namespace std;
void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (int i = 0; i < n1; i++)
L[i] = arr[l + i];
for (int j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
int i = 0, j = 0, k = l;
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(int arr[], int n) {
int curr_size;
for (curr_size = 1; curr_size <= n - 1; curr_size = 2 * curr_size) {
for (int left_start = 0; left_start < n - 1; left_start += 2 * curr_size) {
int mid = min(left_start + curr_size - 1, n - 1);
int right_end = min(left_start + 2 * curr_size - 1, n - 1);
merge(arr, left_start, mid, right_end);
}
}
}
int main() {
int arr[] = { 12, 11, 13, 5, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
return 0;
}
```
该代码中,`merge()`函数实现了将两个有序数组合并成一个有序数组。`mergeSort()`函数实现了迭代法的二路归并排序,其中每次将当前数组分成两个子数组,然后将这两个子数组合并成一个有序数组。最后,在主函数中测试了这个排序算法,输出排序后的结果。
阅读全文