c++归并排序的实现
时间: 2024-01-08 21:21:02 浏览: 100
以下是C++中归并排序的实现示例:
```cpp
#include <iostream>
using namespace std;
void merge(int arr[], int l, int mid, int r) {
int n1 = mid - l + 1;
int n2 = r - mid;
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[mid + 1 + j];
}
int i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k++] = L[i++];
} else {
arr[k++] = R[j++];
}
}
while (i < n1) {
arr[k++] = L[i++];
}
while (j < n2) {
arr[k++] = R[j++];
}
}
void mergeSort(int arr[], int l, int r) {
if (l < r) {
int mid = l + (r - l) / 2;
mergeSort(arr, l, mid);
mergeSort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
}
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int arrSize = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, arrSize - 1);
cout << "Sorted array: ";
for (int i = 0; i < arrSize; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
阅读全文