#include<stdio.h>
int num[1000],a[1000];
void merge_sort(int left, int right)
{
if (left >= right)return;
int l = left, mid = (left + right) / 2, r = mid + 1,k=0;
merge_sort(left, mid);
merge_sort(mid + 1, right);
while (l <= mid && r <= right)
{
if (num[l] > num[r])a[k++] = num[r++];
else a[k++] = num[l++];
}
while (l <= mid)a[k++] = num[l++];
while (r <= right)a[k++] = num[r++];
for (k = 0, l = left; l <= right; l++, k++)num[l] = a[k];
}
int main()
{
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &num[i]);
}
merge_sort(0, n - 1);
for (int i = 0; i < n; i++)
{
printf("%d ", num[i]);
}
}
归并排序(归排)
最新推荐文章于 2024-11-18 16:46:21 发布
本文详细介绍了如何在C语言中使用归并排序算法对整数数组进行排序,通过递归和合并两个已排序部分实现。展示了完整的主函数和merge_sort函数的代码实现过程。
摘要由CSDN通过智能技术生成