#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
//实现合并函数
void merge(int a[], int start, int mid, int end)
{
int tmp[20] = { 0 };
int l = start;
int r = mid + 1;
int k = start;
while (l <= mid && r <= end)
{
if (a[l] <= a[r])
{
tmp[k] = a[l];
k++;
l++;
}
else
{
tmp[k] = a[r];
k++;
r++;
}
}
while (l <= mid)
{
tmp[k] = a[l];
k++;
l++;
}
while (r <= end)
{
tmp[k] = a[r];
k++;
r++;
}
for (int i = start; i <= end; i++)
{
a[i] = tmp[i];
}
return;
}
//递归实现归并排序
int mergesort(int a[], int start, int end)
{
if (start == end)
{
return 0;
}
int mid = (start + end) / 2;
mergesort(a, start, mid);
mergesort(a, mid + 1, end);
merge(a, start, mid, end);
}
int main(void) {
int a[10] = { 4, 2, 3, 1, 8, 6, 9, 2,10, 3 };
mergesort(a, 0, 9);
for (int i = 0; i < 9; i++)
{
printf("%d", a[i]);
}
return 0;
}
归并排序C语言实现
最新推荐文章于 2024-08-22 21:24:01 发布