用C语言实现归并排序
时间: 2023-07-05 10:24:01 浏览: 109
好的,下面是用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];
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++;
}
}
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[] = { 38, 27, 43, 3, 9, 82, 10 };
int size = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
mergeSort(arr, 0, size - 1);
printf("\nSorted array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
这段代码实现了归并排序的核心代码逻辑。在 `merge` 函数中,先将原始数组分为两个子数组,然后将这两个子数组合并成一个有序数组。在 `mergeSort` 函数中,先递归地将左右两个子数组分别排序,然后再合并成一个有序数组。最后在 `main` 函数中对归并排序进行测试。
阅读全文