文件实现归并操作:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
const int N = 100;
void Merge(int* a,int i, int m, int n)
{
int b, j, k;
int temp[N+1];
b = i;
for (j = m+1, k = 1; i <= m && j <= n; ++k)
{
if(a[i] < a[j])
temp[k] = a[i++];
else
temp[k] = a[j++];
}
for (; i <= m;)
temp[k++] = a[i++];
for (; j <= n;)
temp[k++] = a[j++];
for(i = b, k = 1; i <= n;)
a[i++] = temp[k++];
}
void MergeSort(int* a, int s, int t)
{
int m;
if(s < t)
{
m = (s+t)/2;
MergeSort(a, s, m);
MergeSort(a, m+1, t);
Merge(a, s, m, t);
}
}
int main()
{
FILE *fp;
fp = fopen("exp5.txt", "rb");
if(fp == NULL)
{
printf("Error in open your file\n");
exit(0);
}
int a[N+1];
fread(a, sizeof(int), N+1, fp);
MergeSort(a, 1, N);
printf("After sorting:\n");
for (int i = 1; i <= N; i++)
printf("%d\t", a[i]);
printf("\nTime used = %.6lf(seconds)\n", (double)clock()/CLOCKS_PER_SEC);
system("pause");
return 0;
}