写一个C语言归并排序算法
时间: 2023-05-30 08:07:15 浏览: 144
以下是C语言归并排序算法的实现:
```
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int left[], int left_size, int right[], int right_size) {
int i = 0, j = 0, k = 0;
while (i < left_size && j < right_size) {
if (left[i] < right[j]) {
arr[k++] = left[i++];
} else {
arr[k++] = right[j++];
}
}
while (i < left_size) {
arr[k++] = left[i++];
}
while (j < right_size) {
arr[k++] = right[j++];
}
}
void merge_sort(int arr[], int size) {
if (size < 2) {
return;
}
int mid = size / 2;
int left[mid];
int right[size - mid];
for (int i = 0; i < mid; i++) {
left[i] = arr[i];
}
for (int i = mid; i < size; i++) {
right[i - mid] = arr[i];
}
merge_sort(left, mid);
merge_sort(right, size - mid);
merge(arr, left, mid, right, size - mid);
}
int main() {
int arr[] = {5, 2, 4, 6, 1, 3};
int size = sizeof(arr) / sizeof(arr[0]);
printf("原数组:");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
merge_sort(arr, size);
printf("排序后:");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
该算法首先判断数组是否需要排序,如果数组的大小小于2,则数组已经有序,可以直接返回。如果数组需要排序,则将数组分成两半,递归调用归并排序算法对两个子数组进行排序,最后将两个有序子数组合并成一个有序数组。
阅读全文