归并排序分治法C++实现
时间: 2024-03-18 22:37:02 浏览: 77
归并排序是一种经典的分治算法它将一个大问题分解为多个小问题,然后将小问题的解合并起来得到最终的解。下面是归并排序的C++实现:
```cpp
#include <iostream>
using namespace std;
// 合并两个有序数组
void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
// 创建临时数组
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(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
// 分解为子问题
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
// 合并子问题的解
merge(arr, left, mid, right);
}
}
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "原始数组:";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
mergeSort(arr, 0, n - 1);
cout << "排序后的数组:";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
return 0;
}
```
阅读全文