C语言 快速排序 求高手啊 看下我的代码哪有错误
#include<malloc.h>#include<stdio.h>#include<stdlib.h>#defineMAX_SIZE1000000typedefstr...
# include <malloc.h>
# include <stdio.h>
# include <stdlib.h>
# define MAX_SIZE 1000000
typedef struct {
int key;
}element ;
element a[MAX_SIZE];
void Swap(element *a1,element *a2)
{
int temp;
temp = a1->key;
a1->key = a2->key;
a2->key = temp;
}
void quickSort(element a[],int left,int right)
{
int pivot,i,j;
if( left < right )
{
i = left ;
j = right;
pivot = a[left].key;
do{
do i++;while(a[i].key<pivot);
do j--;while(a[i].key>pivot);
if(i<j)Swap(&a[i],&a[j]);
}while(i<j);
}
Swap(&a[left],&a[j]);
quickSort(a,left,j-1);
quickSort(a,j+1,right);
}
int main()
{
int i=0,n=0,num = 1;
FILE *fp1,*fp2;
/*打开要读入数据的文件*/
if((fp1=fopen("input.txt","r"))==NULL)
{
printf("cannot open file\n");
exit(0);
return 0;
}
/*打开要输出数据的文件*/
if((fp2=fopen("output.txt","w"))==NULL)
{
printf("cannot open file\n");
exit(0);
return 0;
}
do{
i=0;
fscanf(fp1,"%d",&n); /*读入一个数字*/
if(n == -1)break; /*判断是否读到结束符,若是跳出循环*/
for(i=0;i<n;i++)
{
fscanf(fp1,"%d",&a[i].key);
}
quickSort(a,0,n);
fprintf(fp2,"case %d:%d",num,n);
for(i=0;i<n;i++)
{
fprintf(fp2,"%d",a[i].key);
}
for(i=0;i<n;i++)
{
a[i].key = 0;//数据清零
}
}while(1);
fclose(fp1);
fclose(fp2);
return 1;
} 展开
# include <stdio.h>
# include <stdlib.h>
# define MAX_SIZE 1000000
typedef struct {
int key;
}element ;
element a[MAX_SIZE];
void Swap(element *a1,element *a2)
{
int temp;
temp = a1->key;
a1->key = a2->key;
a2->key = temp;
}
void quickSort(element a[],int left,int right)
{
int pivot,i,j;
if( left < right )
{
i = left ;
j = right;
pivot = a[left].key;
do{
do i++;while(a[i].key<pivot);
do j--;while(a[i].key>pivot);
if(i<j)Swap(&a[i],&a[j]);
}while(i<j);
}
Swap(&a[left],&a[j]);
quickSort(a,left,j-1);
quickSort(a,j+1,right);
}
int main()
{
int i=0,n=0,num = 1;
FILE *fp1,*fp2;
/*打开要读入数据的文件*/
if((fp1=fopen("input.txt","r"))==NULL)
{
printf("cannot open file\n");
exit(0);
return 0;
}
/*打开要输出数据的文件*/
if((fp2=fopen("output.txt","w"))==NULL)
{
printf("cannot open file\n");
exit(0);
return 0;
}
do{
i=0;
fscanf(fp1,"%d",&n); /*读入一个数字*/
if(n == -1)break; /*判断是否读到结束符,若是跳出循环*/
for(i=0;i<n;i++)
{
fscanf(fp1,"%d",&a[i].key);
}
quickSort(a,0,n);
fprintf(fp2,"case %d:%d",num,n);
for(i=0;i<n;i++)
{
fprintf(fp2,"%d",a[i].key);
}
for(i=0;i<n;i++)
{
a[i].key = 0;//数据清零
}
}while(1);
fclose(fp1);
fclose(fp2);
return 1;
} 展开
2个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询