我正在尝试使用数组实现合并排序。我的代码正在跳入循环而不是停止。我需要使用 Ctrll+Z 来停止我的程序。基本上我正在从文件中读取并将该数组传递给合并排序函数,然后我再次写入文件。写入文件后,我计算编程时间并显示它。请检查我下面的代码。谢谢。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
clock_t start=clock();
void mergesort(int *,int,int);
void merge(int *,int,int,int);
void writesortedrraytofile(int *,int);
static char *opfile=(char *)"output.txt";
int main(int argc,char* argv[])
{
FILE *fp;
char line[80];
int array[1000000];
int i=0,counter;
int choice;
printf("The command line arguments are:\n");
printf("%d %s %s %s\n",argc,argv[0],argv[1],argv[2]);
if(argc==3 && strcmp(argv[0],"./sorting")==0 && strcmp(argv[1],"input1.txt")==0 && strcmp(argv[2],"output.txt")==0)
{
printf("The command line arguments are correct.\n");
}
else
{
printf("The command line arguments are wrong.I am exiting.\n");
exit (0);
}
fp=fopen(argv[1],"r");
while(fgets(line,80,fp) !=NULL)
{
sscanf(line,"%d",&array[i]);
i++;
}
counter=i;
fclose(fp);
mergesort(array,0,counter);
}
return 0;
}
void mergesort(int *temp,int begin,int end)
{
int mid=0;
if(begin<end)
{
mid=(begin+end)/2;
mergesort(temp,begin,mid);
mergesort(temp,mid+1,end);
}
merge(temp,begin,mid,end);
}
void merge(int *temp,int low,int mid,int high)
{
int i,k;
int *tmp = (int *) malloc((high - low +1)* sizeof(int));
int begin1 = low;
int end1 = mid;
int begin2= mid +1;
int end2 = high;
for ( k = 0; begin1 <= end1 && begin2 <= end2; k++)
if (temp[begin1] < temp[begin2])
tmp[k] = temp[begin1 ++];
else
tmp[k] = temp[begin2 ++];
while (begin1 <= end1)
tmp[k++] = temp[begin1 ++];
while (begin2 <= end2)
tmp[k++] = temp[begin2 ++];
for ( i =0;i < high -low +1; i ++)
temp[low +i] = tmp[i];
free(tmp);
writesortedrraytofile(tmp,high-low+1);
return;
}
void writesortedrraytofile(int *ssarray,int len)
{
FILE *fp;
fp=fopen(opfile,"w");
for(int i=0;i<len;i++)
fprintf(fp,"%d\n",ssarray[i]);
fclose(fp);
printf("The output file is generated.Please check it inside the directory.\n");
printf("Time elapsed: %f\n", ((double)clock() - start) / CLOCKS_PER_SEC);
return;
}