给出算法2的c++代码
时间: 2023-11-18 08:05:26 浏览: 60
cprg.rar_算法的C++代码
以下是算法2的C代码:
```c
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
/* Merge the temp arrays back into arr[left..right]*/
i = 0; /* Initial index of first subarray */
j = 0; /* Initial index of second subarray */
k = left; /* Initial index of merged subarray */
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there are any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there are any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void merge_sort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
/* Sort first and second halves */
merge_sort(arr, left, mid);
merge_sort(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]);
printf("Given array is \n");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
merge_sort(arr, 0, n - 1);
printf("\nSorted array is \n");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
```
该代码使用了递归来实现归并排序算法。其中,`merge()`函数用于合并两个已排序的子数组,而`merge_sort()`函数用于对数组进行排序。在`main()`函数中,我们用一个简单的数组来测试算法的正确性。
阅读全文