怎么用C语言编写归并排序
时间: 2024-01-26 19:43:43 浏览: 66
C语言 归并排序
以下是使用C语言编写归并排序的示例代码:
```c
#include <stdio.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[n1], R[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++];
} else {
arr[k++] = R[j++];
}
}
while (i < n1) {
arr[k++] = L[i++];
}
while (j < n2) {
arr[k++] = R[j++];
}
}
void merge_sort(int arr[], int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
merge_sort(arr, left, mid);
merge_sort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
int main() {
int arr[] = {38, 27, 43, 3, 9, 82, 10};
int n = sizeof(arr) / sizeof(arr[0]);
int i;
printf("Original array: \n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
merge_sort(arr, 0, n - 1);
printf("Sorted array: \n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
运行结果:
```
Original array:
38 27 43 3 9 82 10
Sorted array:
3 9 10 27 38 43 82
```
阅读全文