用c语言写归并排序18,2,20,34,12,32,6,16
时间: 2024-05-09 08:21:52 浏览: 45
好的,下面是使用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;
int *L = (int*)malloc(sizeof(int) * n1);
int *R = (int*)malloc(sizeof(int) * n2);
for(i = 0; i < n1; i++)
L[i] = arr[left + i];
for(j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
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++;
}
free(L);
free(R);
}
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[] = {18, 2, 20, 34, 12, 32, 6, 16};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Before Sorting:\n");
for(int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
mergeSort(arr, 0, n - 1);
printf("After Sorting:\n");
for(int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
```
输出结果为:
```
Before Sorting:
18 2 20 34 12 32 6 16
After Sorting:
2 6 12 16 18 20 32 34
```
希望我的回答对您有所帮助!
阅读全文