帮我写一个归并排序的c语言代码
时间: 2023-10-18 07:03:45 浏览: 95
当然可以,以下是一个基于递归实现的归并排序的c语言代码:
```
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int left[], int leftLen, int right[], int rightLen) {
int i, j, k;
i = j = k = 0;
while (i < leftLen && j < rightLen) {
if (left[i] <= right[j]) {
arr[k++] = left[i++];
} else {
arr[k++] = right[j++];
}
}
while (i < leftLen) {
arr[k++] = left[i++];
}
while (j < rightLen) {
arr[k++] = right[j++];
}
}
void mergeSort(int arr[], int arrLen) {
if (arrLen < 2) {
return;
}
int mid = arrLen / 2;
int left[mid];
int right[arrLen - mid];
for (int i = 0; i < mid; i++) {
left[i] = arr[i];
}
for (int i = mid; i < arrLen; i++) {
right[i - mid] = arr[i];
}
mergeSort(left, mid);
mergeSort(right, arrLen - mid);
merge(arr, left, mid, right, arrLen - mid);
}
int main() {
int arr[] = {4, 2, 1, 3, 6, 5, 7};
int arrLen = sizeof(arr) / sizeof(int);
printf("Original array: ");
for (int i = 0; i < arrLen; i++) {
printf("%d ", arr[i]);
}
printf("\n");
mergeSort(arr, arrLen);
printf("Sorted array: ");
for (int i = 0; i < arrLen; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
该代码实现了归并排序的主要逻辑,将一个无序数组按照大小顺序排列。如果您还有其他问题,欢迎随时提出。
阅读全文