C语言自顶向下的二路归并排序算法,C++实现自顶向下的归并排序算法
时间: 2023-06-28 13:05:40 浏览: 129
以下是C语言自顶向下的二路归并排序算法的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int *L = (int*) malloc(sizeof(int) * n1);
int *R = (int*) malloc(sizeof(int) * n2);
int i, j, k;
for (i = 0; i < n1; i++) {
L[i] = arr[left + i];
}
for (j = 0; j < n2; j++) {
R[j] = arr[mid + 1 + j];
}
i = j = 0;
k = left;
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++];
}
free(L);
free(R);
}
void mergeSort(int arr[], int left, int right) {
if (left >= right) return;
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
int main() {
int n = 10, i;
int arr[] = {5, 4, 8, 3, 1, 9, 6, 2, 7, 0};
srand(time(NULL));
printf("Original array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
mergeSort(arr, 0, n-1);
printf("Sorted array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
以下是C++实现自顶向下的归并排序算法的代码:
```c++
#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 = new int[n1];
int *R = new int[n2];
int i, j, k;
for (i = 0; i < n1; i++) {
L[i] = arr[left + i];
}
for (j = 0; j < n2; j++) {
R[j] = arr[mid + 1 + j];
}
i = j = 0;
k = left;
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++];
}
delete[] L;
delete[] R;
}
void mergeSort(int arr[], int left, int right) {
if (left >= right) return;
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
int main() {
int n = 10, i;
int arr[] = {5, 4, 8, 3, 1, 9, 6, 2, 7, 0};
srand(time(NULL));
cout << "Original array: ";
for (i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
mergeSort(arr, 0, n-1);
cout << "Sorted array: ";
for (i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
阅读全文