头文件
#include<stdio.h>
int num = 0;
输出数
void print_data(int data[], int first, int last)
{
int i = 0;
for (i = 0;i < first;i++)
printf("*");
for (i = first;i <= last;i++)
printf("%3d", data[i]);
for (i = last;i <= 8;i++)
printf("*");
printf("\n");
}
一趟归并
void merge(int array[], int first, int last)
{
int mid, i1, i2, i3;
int temp[10];
int i, j;
mid = (first + last) / 2;
i1 = 0;
i2 = first;
i3 = mid + 1;
while (i2 <= mid && i3 <= last)
{
if (array[i2] < array[i3])
temp[i1++] = array[i2++];
else
temp[i1++] = array[i3++];
}
if (i2 <= mid)
{
while(i2<=mid)
temp[i1++] = array[i2++];
}
if (i3 <= last)
{
while(i3<=last)
temp[i1++] = array[i3++];
}
for (i = first, j = 0;i <= last;i++, j++)
array[i] = temp[j];
print_data(array, first, last);
}
归并排序
void mergesort(int data[], int first, int last)
{
int mid;
if (first < last)
{
mid = (first + last) / 2;
mergesort(data, first, mid);
mergesort(data, mid + 1, last);
merge(data, first, last);
}
}
主函数
int main()
{
int a[] = { 1,8,6,4,10,5,3,2,22 };
mergesort(a, 0, 8);
}
运行结果